﻿using BigMonitoringWarningApi.Model.ApiResult;
using GYCTOAManagementSystemNewApi.Controllers;
using GYCTOAManagementSystemNewApi.Controllers.PublicController;
using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Request;
using GYCTOAManagementSystemNewApi.Model.Request.ReProject1;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Transactions;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    //[Authorize]
    public class Project1Controller : Controller
    {


        private readonly ILogger<Project1Controller> _logger;
        DBContext db;
        PublicTool _publictool;
        /// <summary>
        /// 项目备案权限码
        /// </summary>
        const string ProjectRecordRight = "080101";
        /// <summary>
        /// 计划经营部审批权限码
        /// </summary>
        readonly string PalnAudit = ((int)AuditRightPeopleEnum.PlanningDepart).ToString();
        /// <summary>
        /// 内部项目审批权限码
        /// </summary>
        readonly string OperateInAudit = ((int)AuditRightPeopleEnum.InternalApproval).ToString();
        /// <summary>
        /// 外部项目审批权限码
        /// </summary>
        readonly string OperateOutAudit = ((int)AuditRightPeopleEnum.ExternalApproval).ToString();
        /// <summary>
        /// 财务审批权限码
        /// </summary>
        readonly string FinanceAudit = ((int)AuditRightPeopleEnum.FinanceAccounting).ToString();
        /// <summary>
        /// 财务出纳签批
        /// </summary>
        readonly string FinanceCashier = ((int)AuditRightPeopleEnum.FinanceCashier).ToString();
        /// <summary>
        /// 总经理/董事长审批权限码
        /// </summary>
        readonly string ChairmanAudit = ((int)AuditRightPeopleEnum.Chairman).ToString();

        Message message = null;
        public Project1Controller(ILogger<Project1Controller> logger, DBContext _db)
        {
            message = new Message();
            _logger = logger;
            db = _db;
            _publictool = new PublicTool(_db);
        }


        #region 项目财务数据阶段
        /// <summary>
        /// 获取所有的项目财务数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 

        [HttpPost("GetAllProjectFinanceData")]
        public JsonResult GetAllProjectFinanceData([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var projectid = Convert.ToInt32(formData["id"]);
            Project pro = db.Project.Find(projectid);
            return new JsonResult(new { pro = pro });
        }




        [HttpPost("GetFileNames")]
        public ApiResult GetFileNames([FromBody] dynamic formData)
        {
            var Request = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            //流程Id
            var id = Convert.ToInt32(formData["id"]);
            //var a = Request.Form["Single"];
            //log.Error(FileType.ToString());
            //log.Error(Type.ToString());
            //log.Error(id.ToString());
            //log.Error(a.ToString());
            string serverPath = string.Empty;
            List<Files> planFiles = PublicTool.GetFileInfo("项目文件内容", "2\\" + id + "\\1");
            return ApiResult.True(planFiles);
        }


        /// <summary>
        /// 新增或修改项目财务信息
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpPost("UpdateProjectFinance")]
        public JsonResult UpdateProjectFinance([FromBody] dynamic formData)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ');
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            Project project = JsonConvert.DeserializeObject<Project>(jsondata["project"].ToString());
            Project pro = db.Project.Where(x => x.Id == project.Id).FirstOrDefault();
            var TokenValuesArray = TokenManage.GetTokenValues(author[1]);
            var userId = Convert.ToInt32(TokenValuesArray[0].Value);//当前账户ID
            Users user = db.Users.Find(userId);
            Message mess = new Message();
            var right = Convert.ToString(TokenValuesArray[2].Value);
            //if (user.DepartmentId != Convert.ToInt32(AuditRightDepartEnum.FinanceDepart))
            if (!right.Contains(((int)AuditRightPeopleEnum.FinanceAccounting).ToString()) || !right.Contains(((int)AuditRightPeopleEnum.FinanceCashier).ToString()))
            {
                mess.IsSuccess = false;
                mess.Msg = "您无操作权限，请联系财务人员";
                return new JsonResult(new { mess = mess });
            }
            using (var scope = new TransactionScope())
            {
                pro.CollectionAmount = project.CollectionAmount;
                //pro.BadMoney = project.BadMoney;
                //pro.WriteOffTax = project.WriteOffTax;
                //pro.SettleMoney = project.SettleMoney;
                //pro.PersonLoan = project.PersonLoan;
                //pro.PurchaseCost = project.PurchaseCost;
                //pro.LaborCost = project.LaborCost;
                //pro.MaterialCost = project.MaterialCost;
                //pro.MachineryCost = project.MachineryCost;
                //pro.OtherDirectCost = project.OtherDirectCost;
                //pro.SubcontractingCost = project.SubcontractingCost;
                //pro.WriteOffRate = project.WriteOffRate;
                //pro.ManagementPersonCost = project.ManagementPersonCost;
                //pro.WelfareCost = project.WelfareCost;
                //pro.FixedAssetsCost = project.FixedAssetsCost;
                //pro.LowValueCost = project.LowValueCost;
                //pro.OfficeCost = project.OfficeCost;
                //pro.TravelCost = project.TravelCost;
                //pro.BusinessCost = project.BusinessCost;
                //pro.SafetyCost = project.SafetyCost;
                //pro.VehicleCost = project.VehicleCost;
                //pro.OtherIndirectCost = project.OtherIndirectCost;
                //pro.OperatingCost = project.OperatingCost;
                mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
                scope.Complete();
            }
            mess.Msg = mess.IsSuccess ? "操作成功" : "操作失败";
            return new JsonResult(new { mess = mess });
        }
        #endregion

        #region 项目备案阶段视图

        /// <summary>
        /// 项目备案
        /// </summary>
        /// <returns></returns>
       // [BaseActionFilter(OperateRight = ProjectRecordRight)]
        /// <summary>
        /// 项目备案后的立项阶段信息填写
        /// </summary>
        /// <returns></returns>
        /// 

        [HttpPost("ProjectApproval")]
        public JsonResult ProjectApproval([FromBody] dynamic formData)
        {
            var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
            var projectid = Convert.ToInt32(formData["id"]);
            Project obj = db.Project.Find(projectid);
            // var obj = db.Project.Where(l => l.Id == id).FirstOrDefault();
            if (obj == null)
            {
                message.IsSuccess = false;
                message.Msg = "该记录不存在";
                return new JsonResult(new { data = obj, message = message });
            }
            return new JsonResult(new { data = obj });
        }
        #endregion

        #region 项目前期准备视图
        /// <summary>
        /// 项目前期准备工作
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("ProjectPrepare")]
        public ActionResult ProjectPrepare(int id = -1)
        {
            return new JsonResult(new { id = id });
        }
        /// <summary>
        /// 添加项目设备
        /// </summary>
        /// <returns></returns>
        [HttpGet("AddProjectDevice")]
        public ActionResult AddProjectDevice(int ProjectId)
        {
            //   ViewBag.data = JsonConvert.SerializeObject(ProjectId);
            return new JsonResult(new { ProjectId = ProjectId });
        }
        /// <summary>
        /// 修改项目设备
        /// </summary>
        /// <returns></returns>
        /// 
        //[HttpGet("UpdateProjectDevice")]
        //public ActionResult UpdateProjectDevice(int id)
        //{

        //    //var obj = db.ProjectDevice.Where(l => l.Id == id).FirstOrDefault();
        //    //if (obj == null)
        //    //{
        //    //    return Content(PublicTool.WebPopup());
        //    //}
        //    //return View(obj);
        //    ProjectDevice obj = db.ProjectDevice.Find(id);
        //    // var obj = db.Project.Where(l => l.Id == id).FirstOrDefault();
        //    if (obj == null)
        //    {
        //        message.IsSuccess = false;
        //        message.Msg = "该记录不存在";
        //        return new JsonResult(new { data = obj, message = message });
        //    }
        //    else
        //    {
        //        message.IsSuccess = true;
        //        message.Msg = "该记录查询成功";
        //    }
        //    return new JsonResult(new { data = obj, message = message });
        //}
        /// <summary>
        /// 添加项目实施计划
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("AddProjectWorkPlan")]
        public JsonResult AddProjectWorkPlan(int ProjectId)
        {
            return new JsonResult(new { ProjectId = ProjectId });
        }

        /// <summary>
        /// 添加项目人员
        /// </summary>
        /// <returns></returns>
        [HttpGet("AddProjectPeople")]

        public JsonResult AddProjectPeople(int ProjectId)
        {
            return new JsonResult(new { ProjectId = ProjectId });
        }
        
        /// <summary>
        /// 获取当前时间没有负责项目的项目负责人
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetNotDateUser")]
        public async Task<ApiResult> GetNotDateUser([FromBody] dynamic formData)
        {
            /*  var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
              var startDate = Convert.ToDateTime((string)formData["StartDate"]);
              var endDate = Convert.ToDateTime((string)formData["EndDate"]);
              //正在执行的项目过程
              var obj = db.Project.Where(l => (l.StartDate < endDate && l.EndDate > startDate) && !l.Delete).ToList();
              var userids = obj.Select(x => x.HeadUserId).ToList();
              var ids = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
              var userList = db.Users.Where(x => x.RoleId.Equals(ids) && !userids.Contains(x.Id.ToString()) && !x.Delete).ToList();
             */
            var ids = ConfigurationHelper.GetConfigHeadRoleId("HeadRoleId");
            var userList = db.Users.Where(x => x.RoleId.Equals(ids)   && !x.Delete).ToList();

            return ApiResult.True(userList);
        }

        #endregion

        #region 项目日常管理阶段视图
        /// <summary>
        /// 项目日常管理阶段工作
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("ProjectDailyManage")]

        public JsonResult ProjectDailyManage(int id = -1)
        {
            var obj = db.Project.Where(l => l.Id == id).FirstOrDefault();
            if (obj == null)
            {
                message.IsSuccess = false;
                message.Msg = "该记录不存在";
                return new JsonResult(new { data = obj, message = message });
            }
            else
            {
                message.IsSuccess = true;
                message.Msg = "该记录查询成功";
            }
            return new JsonResult(new { data = obj, message = message });
        }
        /// <summary>
        /// 添加项目实施进度
        /// </summary>
        /// <returns></returns>
        /// 

        [HttpGet("AddProjectWorkProgress")]
        public JsonResult AddProjectWorkProgress(int ProjectId)
        {
            return new JsonResult(new { ProjectId = ProjectId });
        }
        
        /// <summary>
        /// 添加项目设备使用记录
        /// </summary>
        /// <returns></returns>
        [HttpGet("ProjectId")]
        public JsonResult AddProjectDeviceUseRecord(int ProjectId)
        {
            return new JsonResult(new { ProjectId = ProjectId });
        }

        /// <summary>
        /// 添加项目工具使用记录
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("AddProjectToolUseRecord")]
        public JsonResult AddProjectToolUseRecord(int ProjectId)
        {
            return new JsonResult(new { ProjectId = ProjectId });
        }

        /// <summary>
        /// 添加项目日志
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("AddProjectJournall")]
        public JsonResult AddProjectJournall(int ProjectId)
        {
            return new JsonResult(new { ProjectId = ProjectId });
        }

        /// <summary>
        /// 添加项目产出计量单
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("AddProjectOutputMeasure")]
        public ActionResult AddProjectOutputMeasure(int ProjectId)
        {

            return new JsonResult(new { ProjectId = ProjectId });
        }
        /// <summary>
        /// 修改项目计量单
        /// </summary>
        /// <returns></returns>
        /// 

        /*
         * 
      /// <summary>
        /// 添加项目支出明细
        /// </summary>
        /// <returns></returns>
        public ActionResult AddProjectExpenseDetail(int ProjectId)
        {
            ViewBag.data = JsonConvert.SerializeObject(ProjectId);
            return View();
        }
    /// <summary>
    /// 添加项目人员考勤
    /// </summary>
    /// <returns></returns>
    public ActionResult AddProjectCheckWork()
    {
        return View();
    }
    /// <summary>
    /// 添加项目人员调动
    /// </summary>
    /// <returns></returns>
    public ActionResult AddProjectPeopleTransfer()
    {
        return View();
    }
    /// <summary>
    /// 添加项目设备调动
    /// </summary>
    /// <returns></returns>
    public ActionResult AddProjectDeviceTransfer()
    {
        return View();
    }
    #endregion

    #region 项目后期总结阶段视图
    /// <summary>
    /// 项目总结页面
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectSummary(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View(id);
    }
    #endregion

    #region 项目财务视图
    /// <summary>
    /// 项目总结页面
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectFinance(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View(id);
    }
    #endregion



    #region 项目报表视图
    /// <summary>
    /// 项目报表
    /// </summary>
    /// <returns></returns>
    /// 

    [HttpGet("ProjectReport")]
    public JsonResult ProjectReport(int id)
    {
        var obj = db.Project.Where(l => l.Id == id).FirstOrDefault();
        if (obj == null)
        {
            message.IsSuccess = false;
            message.Msg = "该记录不存在";
            return new JsonResult(new { data = obj, message = message });
        }
        else
        {
            message.IsSuccess = true;
            message.Msg = "该记录查询成功";
        }
        return new JsonResult(new { data = obj, message = message });
    }
    /// <summary>
    /// 项目备案报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectRecordlReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目立项申请报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectApprovalReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目立项任务书报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectTaskReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目资金计划报表一
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectCapitalPlanReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目资金计划报表二
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectCapitalPlanTwoReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目设备使用计划报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectDeviceReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目工作计划报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectWorkPlanReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目人员计划报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectPeopleReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目实施进度报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectWorkProgressReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目设备使用台账
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectDeviceUseRecordReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目工具使用台账
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectToolUseRecordReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目人员考勤报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectCheckWorkReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目日志数据页面
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectJournalDataPage(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目日志报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectJournalReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目设备调动数据页面
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectDeviceTransferDataPage(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目设备调动报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectDeviceTransferReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目人员调动数据页面
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectPeopleTransferDataPage(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目人员调动报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectPeopleTransferReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目产出计量报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectOutputMeasureReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目借款使用明细报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectExpenseDetailReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目设计开发评审报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectDesignDevReviewReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目评审意见跟踪报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectReviewTrackReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目变更申请报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectChangeApplyReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目变更通知报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectChangeNoticeReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目终止申请报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectEndApplyReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目终止通知报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectEndNoticeReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    /// <summary>
    /// 项目总结报表
    /// </summary>
    /// <returns></returns>
    public ActionResult ProjectSummaryReport(int id)
    {
        ViewBag.data = JsonConvert.SerializeObject(id);
        return View();
    }
    #endregion


    */
        #region 项目物资视图
        /// <summary>
        /// 项目物资库
        /// </summary>
        /// <returns></returns>
        [HttpGet("ProjectMaterial")]
        public JsonResult ProjectMaterial(int id = -1)
        {
            var obj = db.Project.Where(l => l.Id == id).FirstOrDefault();
            if (obj == null)
            {
                message.IsSuccess = false;
                message.Msg = "该记录不存在";
                return new JsonResult(new { data = obj, message = message });
            }
            else
            {
                message.IsSuccess = true;
                message.Msg = "该记录查询成功";
            }
            return new JsonResult(new { data = obj, message = message });
        }

        #endregion



        #region 第一版项目视图和接口
        private Project GetProject(int Id)
        {
            return db.Project.Where(l => l.Id == Id && l.Delete != true).FirstOrDefault();
        }
        [HttpPost("DeleteProjectContent")]
        public JsonResult DeleteProjectContent([FromBody] int[] arrDel)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            Message mes = new Message();
            foreach (var t in arrDel)
            {
                var obj = GetProject(t);
                if (obj == null)
                {
                    mes.IsSuccess = false;
                    mes.Msg = "该数据不存在";
                    return new JsonResult(new { mes = mes });
                }
                //db.Project.Remove(obj);
                obj.Delete = true;
                obj.OperatId = userId;
                obj.OperatDate = DateTime.Now;
                //删除文件
                //var path = AppDomain.CurrentDomain.BaseDirectory;
                //var root = Path.GetPathRoot(path);
                //string serverPath = root + "CompanyFile\\" + "1\\" + (int)FileTypeEnum.Project+ "\\" + t; ;//1代表OA系统
                //Public.DeleteFile(serverPath,true);
            }
            mes.IsSuccess = db.SaveChanges() > 0;
            mes.Msg = mes.IsSuccess ? "删除成功" : "删除失败";
            return new JsonResult(new { mes = mes });
        }
        [HttpPost("UpdateProjectContent")]
        public JsonResult UpdateProjectContent(Project project)
        {
            var entry = db.Entry<Project>(project);
            entry.State = (Microsoft.EntityFrameworkCore.EntityState)System.Data.Entity.EntityState.Unchanged;
            entry.Property(t => t.ProjectNumber).IsModified = true; //设置要更新的属性
            entry.Property(t => t.HeadUserId).IsModified = true; //设置要更新的属性
            entry.Property(t => t.ProjectName).IsModified = true; //设置要更新的属性
                                                                  //    entry.Property(t => t.PartA).IsModified = true; //设置要更新的属性
            entry.Property(t => t.EstimatedContractAmount).IsModified = true; //设置要更新的属性
            entry.Property(t => t.CollectionAmount).IsModified = true; //设置要更新的属性
            entry.Property(t => t.Remark).IsModified = true; //设置要更新的属性
            var flag = db.SaveChanges() > 0 ? true : false;
            return new JsonResult(new { data = project.Id });
        }
        [HttpPost("AddProjectContent")]
        public JsonResult AddProjectContent(Project project)
        {
            var flag = false;
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            project.OperatId = userId;
            try
            {
                db.Project.Add(project);
                flag = db.SaveChanges() > 0 ? true : false;
            }
            catch (Exception ex)
            {
                message.IsSuccess = false;
                message.Msg = "数据添加失败";
                return new JsonResult(new { data = "", message = message });
            }
            message.IsSuccess = true;
            message.Msg = "数据添加成功";
            return new JsonResult(new { data = project.Id, message = message });
        }
        /// <summary>
        /// 项目详情获取
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetProjectDetail")]
        public JsonResult GetProjectDetail([FromBody] dynamic formData)
        {
            // (string StartDate, string EndDate, int limit, int offset, Project project, bool NoApproval)
            string jsonstring = formData.ToString();
            JToken j_token = JsonConvert.DeserializeObject<JToken>(jsonstring);
            Project project = JsonConvert.DeserializeObject<Project>(j_token["Project"].ToString());
            int offset = Convert.ToInt32(j_token["currentPage"]);
            int limit = Convert.ToInt32(j_token["pagesize"]);
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);

            //var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            //var logid = TokenManage.GetTokenValues(author)[0].Value;
            //var right = TokenManage.GetTokenValues(author)[2].Value;
            //int userId = Convert.ToInt32(logid);
            if (right != "Admin")
            {
                project.HeadUserId = userid + "";
            }
            var sql = "select * from Project where 1=1 ";
            if (project.HeadUserId != null && project.HeadUserId != "")
            {
                sql += "and HeadUserId='" + project.HeadUserId + "' ";
            }
            if (project.Id > 0)
            {
                sql += "and Id='" + project.Id + "' ";
            }
            if (j_token["StartDate"] != null && j_token["StartDate"].ToString() != "")
            {
                sql += "and Date(StartDate) >='" + j_token["StartDate"].ToString() + "' ";
            }
            if (j_token["EndDate"] != null && j_token["EndDate"].ToString() != "")
            {
                sql += "and Date(StartDate) <='" + j_token["EndDate"].ToString() + "' ";
            }
            List<Project> oldlist = new List<Project>();
            var query = db.Project.FromSqlRaw(sql).OrderByDescending(x => x.Id).Where(x => !x.Delete).ToList();
            oldlist = query.OrderByDescending(x => x.OperatDate).ToList();
            List<Project> list = new List<Project>();

            #region 根据数据查看权限剔除数据
            if (!right.Contains(PublicTool.Admin))
            {
                //只能查看自己提交的单据或者自己有审批权限的单据
                try
                {
                    foreach (var l in oldlist)
                    {
                        if (l.HeadUserId == userid.ToString())
                        {
                            list.Add(l);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);

                }

            }
            else
            {
                list = oldlist;
            }
            #endregion
            var total = list.Count;
            var rows = list.Take(limit * offset).Skip(limit * (offset - 1)).ToList();
            //var ret = JsonConvert.SerializeObject(rows, setting);
            return Json(new { code = 0, msg = "", count = total, data = rows });
        }

        /// <summary>
        /// 修改当前项目状态
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost("SetProjectEndById")]
        public ApiResult SetProjectEndById([FromBody] SetProjectEndById data)
        {
            try
            {
                var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
                var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
                var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
                if (right != "Admin")
                {
                    return ApiResult.False("对不起，您当前无权限修改当前项目的状态");

                }
                var project = db.Project.FirstOrDefault(x => x.Id == data.ProjectId);
                project.ProjectStatus = data.ProjectStatus;
                db.Update(project);
                db.SaveChanges();
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False(ex.Message);
            }
        } 

        private string ArraySortToString(string str, string separator)
        {
            string[] sArray = Regex.Split(str, separator, RegexOptions.IgnoreCase);
            int[] nArray = Array.ConvertAll<string, int>(sArray, int.Parse);
            List<int> lArray = nArray.ToList();
            lArray.Sort();//从大到小
            var restult = String.Join(",", lArray);
            return restult;
        }
        #endregion 

        #region 项目统计接口，用于首页展示
        /// <summary>
        /// 获取进行中的项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetProjectOn")]
        public JsonResult GetProjectOn()
        {
            var obj = db.Project.Where(x => !x.Delete && x.ProjectStatus==0).ToList();
            return Json(obj);
        }
        /// <summary>
        /// 获取已完成的项目
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetProjectFinish")]
        public JsonResult GetProjectFinish()
        {
            var obj = db.Project.Where(x => !x.Delete && x.ProjectStatus == 1/* && x.FinishDate < DateTime.Now*/).ToList();
            return Json(obj);
        }
        #endregion

        #region 项目立项阶段
        /// <summary>
        /// 项目立项阶段数据获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[HttpGet("GetAllRecordData")]
        //public JsonResult GetAllRecordData(int id)
        //{
        //    ProjectApproval projectApproval = db.ProjectApproval.Where(x => x.ProjectId == id).FirstOrDefault();
        //    ProjectTask projectTask = db.ProjectTask.Where(x => x.ProjectId == id).FirstOrDefault();
        //    ProjectCapitalPlan projectCapitalPlanOne = db.ProjectCapitalPlan.Where(x => x.ProjectId == id && x.Type == 1).FirstOrDefault();
        //    ProjectCapitalPlan projectCapitalPlanTwo = db.ProjectCapitalPlan.Where(x => x.ProjectId == id && x.Type == 2).FirstOrDefault();
        //    List<ProjectPeople> projectPeople = db.ProjectPeople.Where(x => x.ProjectId == id && !x.Delete && (x.DataSources == (int)ProjectPeopleDataSourceEnum.Approval || x.DataSources == (int)ProjectPeopleDataSourceEnum.Task)).ToList();
        //    return Json(new { projectApproval, projectTask, projectCapitalPlanOne, projectCapitalPlanTwo, projectPeople });
        //}
        /// <summary>
        /// 项目备案
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpPost("AddProjectRecord")]
        [CustomerActionFilter(OperateRight = ProjectRecordRight)]
        public ApiResult AddProjectRecord([FromBody] dynamic formData)
        {
            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
            Project project = JsonConvert.DeserializeObject<Project>(j_token["Project"].ToString());

            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var logid = TokenManage.GetTokenValues(author)[0].Value;
            var right = TokenManage.GetTokenValues(author)[2].Value;
            int userId = Convert.ToInt32(logid);

            var flag = false;
            project.OperatId = userId;
            project.OperatDate = DateTime.Now;
            try
            {
                db.Project.Add(project);
                project.ProjectNumber = "HD" + DateTime.Now.ToString("yyyyMMddHHmmss");
                flag = db.SaveChanges() > 0 ? true : false;
            }
            catch (DbEntityValidationException dbEx)
            {
                return ApiResult.False(project);
            }
            return ApiResult.True(project);
        }
        /// <summary>
        /// 备案信息修改
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpPost("UpdateProjectRecord")]
        // [CustomerActionFilter(OperateRight = ProjectRecordRight)]
        public ApiResult UpdateProjectRecord([FromBody] UpdateProjectRecordRequset updateProjectRecordRequset)
        {

            db.Project.Update(updateProjectRecordRequset.project);
            db.SaveChanges();
            return ApiResult.True();
        }
        /// <summary>
        /// 新增或修改项目申请表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectApproval")]
        //public JsonResult UpdateProjectApproval([FromBody] dynamic formData)
        //{
        //    // (Project project, ProjectApproval projectApproval, List<ProjectPeople> ProjectPeople)
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    Project project = JsonConvert.DeserializeObject<Project>(j_token["project"].ToString());
        //    ProjectApproval projectApproval = JsonConvert.DeserializeObject<ProjectApproval>(j_token["ProjectApproval"].ToString());
        //    List<ProjectPeople> ProjectPeople = JsonConvert.DeserializeObject<List<ProjectPeople>>(j_token["ProjectPeople"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var logid = TokenManage.GetTokenValues(author)[0].Value;
        //    var right = TokenManage.GetTokenValues(author)[2].Value;
        //    int userId = Convert.ToInt32(logid);

        //    PublicMethodApiController pubc = new PublicMethodApiController(db);

        //    Project pro = db.Project.Where(x => x.Id == projectApproval.ProjectId).FirstOrDefault();
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        if (!pubc.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return Json(mess);
        //        }
        //        //项目备案信息
        //        //pro.CreateDate = project.CreateDate;
        //        //pro.FinishDate = project.FinishDate;
        //        ////pro.ContractAmount = project.ContractAmount;
        //        //pro.ContractId = project.ContractId;
        //        //pro.Bond = project.Bond;
        //        projectApproval.OperatDate = DateTime.Now;
        //        projectApproval.OperatId = userId;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectApproval.Id == 0)
        //        {
        //            //项目申请表
        //            db.ProjectApproval.Add(projectApproval);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectApproval appro = db.ProjectApproval.Where(x => x.Id == projectApproval.Id).FirstOrDefault();
        //            appro.AcceptancIndex = projectApproval.AcceptancIndex;
        //            appro.ManMachine = projectApproval.ManMachine;
        //            appro.OverviewOfExpected = projectApproval.OverviewOfExpected;
        //            appro.BuildUnit = projectApproval.BuildUnit;
        //            appro.DesignUnit = projectApproval.DesignUnit;
        //            appro.ReconnaissanceUnit = projectApproval.ReconnaissanceUnit;
        //            appro.ConstructionControlUnit = projectApproval.ConstructionControlUnit;
        //            appro.ConstructionUnit = projectApproval.ConstructionUnit;
        //            appro.QualityInspectionUnit = projectApproval.QualityInspectionUnit;
        //            appro.BuildPlace = projectApproval.BuildPlace;
        //            appro.BaseType = projectApproval.BaseType;
        //            appro.OtherUnit = projectApproval.OtherUnit;
        //            appro.ProjectInstructorAmount = projectApproval.ProjectInstructorAmount;
        //            appro.ProjectLeaderAmount = projectApproval.ProjectLeaderAmount;
        //            appro.OtherProjectManAmount = projectApproval.OtherProjectManAmount;
        //            appro.ArtisanAmount = projectApproval.ArtisanAmount;
        //            appro.ArtisanWork = projectApproval.ArtisanWork;
        //            appro.ConstructionerAmount = projectApproval.ConstructionerAmount;
        //            appro.ConstructionerWork = projectApproval.ConstructionerWork;
        //            appro.OutsideStaffAmount = projectApproval.OutsideStaffAmount;
        //            appro.OutsideStaffWork = projectApproval.OutsideStaffWork;
        //            appro.OutputValue = projectApproval.OutputValue;
        //            appro.BusinessRisk = projectApproval.BusinessRisk;
        //            appro.ProductionRisk = projectApproval.ProductionRisk;
        //            appro.OtherRisk = projectApproval.OtherRisk;
        //            appro.OperatId = projectApproval.OperatId;
        //            appro.OperatDate = projectApproval.OperatDate;
        //            //申请表中的人员配置
        //            var peoples = db.ProjectPeople.Where(x => x.ProjectId == pro.Id && x.DataSources == (int)ProjectPeopleDataSourceEnum.Approval).ToList();
        //            foreach (var p in peoples)
        //            {
        //                db.ProjectPeople.Remove(p);
        //            }
        //        }
        //        //添加人员配置
        //        if (ProjectPeople != null)
        //        {
        //            foreach (var peo in ProjectPeople)
        //            {
        //                var user = db.Users.Where(x => x.Id == peo.Userid).FirstOrDefault();
        //                peo.ProjectId = pro.Id;
        //                peo.RoleId = user.RoleId;
        //                peo.UserName = user.UserName;
        //                peo.DataSources = (int)ProjectPeopleDataSourceEnum.Approval;
        //                peo.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
        //                peo.OperatDate = DateTime.Now;
        //                peo.OperatId = userId;
        //                db.ProjectPeople.Add(peo);
        //            }
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}
        /// <summary>
        /// 新增或修改项目任务书
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectTask")]
        //public JsonResult UpdateProjectTask([FromBody] dynamic formData)
        //{
        //    //Project project, ProjectTask projectTask, List<ProjectPeople> ProjectPeople)
        //    var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
        //    var project = JsonConvert.DeserializeObject<Project>(jsondata["project"].ToString());
        //    var projectTask = JsonConvert.DeserializeObject<ProjectTask>(jsondata["projectTask"].ToString());
        //    var ProjectPeople = JsonConvert.DeserializeObject<List<ProjectPeople>>(jsondata["ProjectPeople"].ToString());
        //    Project pro = db.Project.Where(x => x.Id == projectTask.ProjectId).FirstOrDefault();
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);

        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return new JsonResult(new { msg = mess });
        //        }
        //        pro.HeadUserId = project.HeadUserId;
        //        projectTask.OperatDate = DateTime.Now;
        //        projectTask.OperatId = userid;
        //        if (projectTask.Id == 0)
        //        {
        //            db.ProjectTask.Add(projectTask);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectTask task = db.ProjectTask.Where(x => x.Id == projectTask.Id).FirstOrDefault();
        //            task.HeadUserWork = projectTask.HeadUserWork;
        //            task.MaterialManager = projectTask.MaterialManager;
        //            task.MaterialManagerWork = projectTask.MaterialManagerWork;
        //            task.Bookkeeper = projectTask.Bookkeeper;
        //            task.BookkeeperWork = projectTask.BookkeeperWork;
        //            task.SecurityOfficer = projectTask.SecurityOfficer;
        //            task.SecurityOfficerWork = projectTask.SecurityOfficerWork;
        //            task.Technician = projectTask.Technician;
        //            task.TechnicianWork = projectTask.TechnicianWork;
        //            task.Constructors = projectTask.Constructors;
        //            task.ConstructionerWork = projectTask.ConstructionerWork;
        //            task.OutsideStaffAmount = projectTask.OutsideStaffAmount;
        //            task.OutsideStaffWork = projectTask.OutsideStaffWork;
        //            task.PlannedCapital = projectTask.PlannedCapital;
        //            task.ApprovedFunds = projectTask.ApprovedFunds;
        //            task.Fudonglv = projectTask.Fudonglv;
        //            task.FirstStageProcedure = projectTask.FirstStageProcedure;
        //            task.FirstStageEffect = projectTask.FirstStageEffect;
        //            task.SecondStageProcedure = projectTask.SecondStageProcedure;
        //            task.SecondStageEffect = projectTask.SecondStageEffect;
        //            task.ThirdStageProcedure = projectTask.ThirdStageProcedure;
        //            task.ThirdStageEffect = projectTask.ThirdStageEffect;
        //            task.FourthStageProcedure = projectTask.FourthStageProcedure;
        //            task.FourthStageEffect = projectTask.FourthStageEffect;
        //            task.OperatId = projectTask.OperatId;
        //            task.OperatDate = projectTask.OperatDate;
        //        }
        //        if (ProjectPeople.Count > 0)
        //        {
        //            //申请表中的人员配置
        //            var peoples = db.ProjectPeople.Where(x => x.ProjectId == pro.Id && x.DataSources == (int)ProjectPeopleDataSourceEnum.Task).ToList();
        //            foreach (var p in peoples)
        //            {
        //                db.ProjectPeople.Remove(p);
        //            }
        //        }
        //        //添加人员配置
        //        foreach (var peo in ProjectPeople)
        //        {
        //            var user = db.Users.Where(x => x.Id == peo.Userid).FirstOrDefault();
        //            peo.ProjectId = pro.Id;
        //            peo.RoleId = user.RoleId;
        //            peo.UserName = user.UserName;
        //            peo.DataSources = (int)ProjectPeopleDataSourceEnum.Task;
        //            peo.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
        //            peo.OperatDate = DateTime.Now;
        //            peo.OperatId = userid;
        //            db.ProjectPeople.Add(peo);
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}
        /// <summary>
        /// 新增或修改项目资金计划表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectCapitalPlan")]
        //public JsonResult UpdateProjectCapitalPlan([FromBody] dynamic formData)
        //{
        //    var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
        //    ProjectCapitalPlan projectCapitalPlan = JsonConvert.DeserializeObject<ProjectCapitalPlan>(jsondata["projectCapitalPlan"].ToString());
        //    Project project = JsonConvert.DeserializeObject<Project>(jsondata["project"].ToString());
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    using (var scope = new TransactionScope())
        //    {
        //        db.Project.Update(project);
        //        if (userid != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return Json(mess);
        //        }
        //        projectCapitalPlan.OperatDate = DateTime.Now;
        //        projectCapitalPlan.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectCapitalPlan.Id == 0)
        //        {
        //            db.ProjectCapitalPlan.Add(projectCapitalPlan);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectCapitalPlan Capital = db.ProjectCapitalPlan.Where(x => x.Id == projectCapitalPlan.Id).FirstOrDefault();
        //            Capital.MaterialCost = projectCapitalPlan.MaterialCost;
        //            Capital.MaterialCostDes = projectCapitalPlan.MaterialCostDes;
        //            Capital.NewTools = projectCapitalPlan.NewTools;
        //            Capital.NewToolsDes = projectCapitalPlan.NewToolsDes;
        //            Capital.NewDevice = projectCapitalPlan.NewDevice;
        //            Capital.NewDeviceDes = projectCapitalPlan.NewDeviceDes;
        //            Capital.OfficeExpenses = projectCapitalPlan.OfficeExpenses;
        //            Capital.OfficeExpensesDes = projectCapitalPlan.OfficeExpensesDes;
        //            Capital.TravelExpenses = projectCapitalPlan.TravelExpenses;
        //            Capital.TravelExpensesDes = projectCapitalPlan.TravelExpensesDes;
        //            Capital.LivingExpenses = projectCapitalPlan.LivingExpenses;
        //            Capital.LivingExpensesType = projectCapitalPlan.LivingExpensesType;
        //            Capital.HotelExpense = projectCapitalPlan.HotelExpense;
        //            Capital.HotelExpenseType = projectCapitalPlan.HotelExpenseType;
        //            Capital.TrainingFee = projectCapitalPlan.TrainingFee;
        //            Capital.TrainingFeeDes = projectCapitalPlan.TrainingFeeDes;
        //            Capital.EquipmentRentalFee = projectCapitalPlan.EquipmentRentalFee;
        //            Capital.EquipmentRentalFeeDes = projectCapitalPlan.EquipmentRentalFeeDes;
        //            Capital.EquipmentFuelCost = projectCapitalPlan.EquipmentFuelCost;
        //            Capital.EquipmentFuelCostDes = projectCapitalPlan.EquipmentFuelCostDes;
        //            Capital.MaintenanceCost = projectCapitalPlan.MaintenanceCost;
        //            Capital.MaintenanceCostDes = projectCapitalPlan.MaintenanceCostDes;
        //            Capital.BusinessEntertainment = projectCapitalPlan.BusinessEntertainment;
        //            Capital.BusinessEntertainmentDes = projectCapitalPlan.BusinessEntertainmentDes;
        //            Capital.LaborCost = projectCapitalPlan.LaborCost;
        //            Capital.LaborCostDes = projectCapitalPlan.LaborCostDes;
        //            Capital.LabourInsuranceArticles = projectCapitalPlan.LabourInsuranceArticles;
        //            Capital.LabourInsuranceArticlesDes = projectCapitalPlan.LabourInsuranceArticlesDes;
        //            Capital.Freight = projectCapitalPlan.Freight;
        //            Capital.FreightDes = projectCapitalPlan.FreightDes;
        //            Capital.ConsultationFee = projectCapitalPlan.ConsultationFee;
        //            Capital.ConsultationFeeDes = projectCapitalPlan.ConsultationFeeDes;
        //            Capital.OtherExpenses = projectCapitalPlan.OtherExpenses;
        //            Capital.OtherExpensesDes = projectCapitalPlan.OtherExpensesDes;
        //            Capital.OperatId = projectCapitalPlan.OperatId;
        //            Capital.OperatDate = projectCapitalPlan.OperatDate;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}
        #endregion

        #region 项目前期准备阶段
        /// <summary>
        /// 获取准备阶段的所有数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[HttpPost("GetAllPrepareData")]
        //public JsonResult GetAllPrepareData([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int id = Convert.ToInt32(j_token["id"].ToString());
        //    List<ProjectWorkPlan> projectWorkPlans = db.ProjectWorkPlan.Where(x => x.ProjectId == id && !x.Delete).ToList();
        //    List<ProjectDevice> projectDevices = db.ProjectDevice.Where(x => x.ProjectId == id && !x.Delete && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
        //    List<ProjectPeople> projectPeople = db.ProjectPeople.Where(x => x.ProjectId == id && !x.Delete && x.DataSources == (int)ProjectPeopleDataSourceEnum.PeoplePlan && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
        //    List<Files> planFiles = PublicTool.GetFileInfo("施工方案", "2\\" + id + "\\4");
        //    List<Files> applicationFiles = PublicTool.GetFileInfo("项目开工申请报告", "2\\" + id + "\\8");
        //    List<Files> otherFiles = PublicTool.GetFileInfo("其他", "2\\" + id + "\\256");
        //    return Json(new { projectWorkPlans, projectDevices, projectPeople, planFiles, applicationFiles, otherFiles });
        //}
        /// <summary>
        /// 新增项目设备使用计划表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("AddProjectDevice")]
        //public JsonResult AddProjectDevice([FromBody] dynamic formData)
        //{
        //    //Project project, ProjectTask projectTask, List<ProjectPeople> ProjectPeople)
        //    var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
        //    var projectDevice = JsonConvert.DeserializeObject<ProjectDevice>(jsondata["projectDevice"].ToString());
        //    //     ProjectDevice projectDevice)
        //    // {
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        var project = db.Project.Where(x => x.Id == projectDevice.ProjectId).FirstOrDefault();
        //        if (userid != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return new JsonResult(new { mess = mess });
        //        }
        //        projectDevice.OperatDate = DateTime.Now;
        //        projectDevice.OperatId = userid;
        //        projectDevice.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
        //        db.ProjectDevice.Add(projectDevice);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return new JsonResult(new { mess = mess });
        //}
        /// <summary>
        /// 前期准备--修改项目设备使用计划表
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectDevice")]
        //public JsonResult UpdateProjectDevice([FromBody] dynamic formData)
        //{
        //    //Project project, ProjectTask projectTask, List<ProjectPeople> ProjectPeople)
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var jsondata = (JToken)JsonConvert.DeserializeObject(formData.ToString());
        //    var projectDevice = JsonConvert.DeserializeObject<ProjectDevice>(jsondata["projectDevice"].ToString());
        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //项目申请表
        //        ProjectDevice device = db.ProjectDevice.Where(x => x.Id == projectDevice.Id && !x.Delete).FirstOrDefault();
        //        var project = db.Project.Where(x => x.Id == device.ProjectId).FirstOrDefault();
        //        if (userid != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return new JsonResult(new { mess = mess });
        //        }
        //        device.DeviceName = projectDevice.DeviceName;
        //        device.DeviceModel = projectDevice.DeviceModel;
        //        device.Amount = projectDevice.Amount;
        //        device.Unit = projectDevice.Unit;
        //        device.ApproachDate = projectDevice.ApproachDate;
        //        device.WorkPoint = projectDevice.WorkPoint;
        //        device.Remark = projectDevice.Remark;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mess = mess });
        //}
        /// <summary>
        /// 新增项目工作实施计划表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("AddProjectWorkPlan")]
        //public JsonResult AddProjectWorkPlan([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectWorkPlan projectWorkPlan = JsonConvert.DeserializeObject<ProjectWorkPlan>(j_token["projectWorkPlan"].ToString());
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var logid = TokenManage.GetTokenValues(author)[0].Value;
        //    // var right = TokenManage.GetTokenValues(author)[2].Value;
        //    int userId = Convert.ToInt32(logid);
        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        var project = db.Project.Where(x => x.Id == projectWorkPlan.ProjectId).FirstOrDefault();
        //        if (userId != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return Json(new { result = mess, projectWorkPlan = "" });
        //        }
        //        projectWorkPlan.OperatDate = DateTime.Now;
        //        projectWorkPlan.OperatId = userId;
        //        db.ProjectWorkPlan.Add(projectWorkPlan);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return Json(new { result = mess, projectWorkPlan = projectWorkPlan });
        //}
        /// <summary>
        /// 修改项目工作实施计划表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectWorkPlan")]
        //public JsonResult UpdateProjectWorkPlan([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectWorkPlan projectWorkPlan = JsonConvert.DeserializeObject<ProjectWorkPlan>(j_token["projectWorkPlan"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var logid = TokenManage.GetTokenValues(author)[0].Value;
        //    // var right = TokenManage.GetTokenValues(author)[2].Value;
        //    int userid = Convert.ToInt32(logid);
        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //项目申请表
        //        ProjectWorkPlan workPlan = db.ProjectWorkPlan.Where(x => x.Id == projectWorkPlan.Id && !x.Delete).FirstOrDefault();
        //        var project = db.Project.Where(x => x.Id == workPlan.ProjectId).FirstOrDefault();
        //        if (userid != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return Json(mess);
        //        }
        //        workPlan.Price = projectWorkPlan.Price;
        //        workPlan.EngineState = projectWorkPlan.EngineState;
        //        workPlan.ConstructionProcedure = projectWorkPlan.ConstructionProcedure;
        //        workPlan.ConstructionContents = projectWorkPlan.ConstructionContents;
        //        workPlan.TotalQuantity = projectWorkPlan.TotalQuantity;
        //        workPlan.PlanStartDate = projectWorkPlan.PlanStartDate;
        //        workPlan.PlanEndDate = projectWorkPlan.PlanEndDate;
        //        workPlan.Planner = projectWorkPlan.Planner;
        //        workPlan.PlanningMaterials = projectWorkPlan.PlanningMaterials;
        //        workPlan.PlanningMachinery = projectWorkPlan.PlanningMachinery;
        //        workPlan.Remark = projectWorkPlan.Remark;
        //        workPlan.Unit = projectWorkPlan.Unit;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}
        /// <summary>
        /// 新增项目人员配置信息
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("AddProjectPeople")]
        //public JsonResult AddProjectPeople([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectPeople projectPeople = JsonConvert.DeserializeObject<ProjectPeople>(j_token["projectPeoplePage"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var logid = TokenManage.GetTokenValues(author)[0].Value;
        //    int userid = Convert.ToInt32(logid);

        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        var project = db.Project.Where(x => x.Id == projectPeople.ProjectId).FirstOrDefault();
        //        if (userid != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author, userid))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return Json(mess);
        //        }
        //        projectPeople.OperatDate = DateTime.Now;
        //        projectPeople.OperatId = userid;
        //        projectPeople.DataSources = (int)ProjectPeopleDataSourceEnum.PeoplePlan;
        //        if (projectPeople.Type == (int)ProjectPeopleTypeEnum.FullTime)
        //        {
        //            var user = db.Users.Where(x => x.Id == projectPeople.Userid).FirstOrDefault();
        //            projectPeople.RoleId = user.RoleId;
        //            projectPeople.UserName = user.UserName;
        //        }
        //        projectPeople.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
        //        projectPeople.OperatDate = DateTime.Now;
        //        projectPeople.OperatId = userid;
        //        db.ProjectPeople.Add(projectPeople);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return Json(new { result = mess, projectPeople = projectPeople });
        //}
        /// <summary>
        /// 修改项目人员配置信息
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectPeople")]
        //public JsonResult UpdateProjectPeople([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectPeople projectPeople = JsonConvert.DeserializeObject<ProjectPeople>(j_token["projectPeople"].ToString());
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    Message mess = new Message();
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    PublicMethodApiController pub = new PublicMethodApiController(db);
        //    using (var scope = new TransactionScope())
        //    {
        //        //项目申请表
        //        ProjectPeople people = db.ProjectPeople.Where(x => x.Id == projectPeople.Id && !x.Delete).FirstOrDefault();
        //        var project = db.Project.Where(x => x.Id == people.ProjectId).FirstOrDefault();
        //        if (userid != Convert.ToInt32(project.HeadUserId))
        //        //if (!pub.IsDepartMember(Convert.ToInt32(AuditRightDepartEnum.ProjectManage), author))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.ProjectManageRight);
        //            return Json(mess);
        //        }
        //        people.Type = projectPeople.Type;
        //        if (people.Type == (int)ProjectPeopleTypeEnum.FullTime)
        //        {
        //            var user = db.Users.Where(x => x.Id == projectPeople.Userid).FirstOrDefault();
        //            people.RoleId = user.RoleId;
        //            people.UserName = user.UserName;
        //        }
        //        else if (people.Type == (int)ProjectPeopleTypeEnum.PartTime)
        //        {
        //            people.UserName = projectPeople.UserName;
        //            people.Age = projectPeople.Age;
        //            people.LaborCost = projectPeople.LaborCost;
        //        }
        //        people.Skill = projectPeople.Skill;
        //        people.WorkContent = projectPeople.WorkContent;
        //        people.WorkCycle = projectPeople.WorkCycle;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}

        /// <summary>
        /// 添加项目参与人
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpPost("UpProject")]
        public ApiResult UpProject([FromBody] dynamic formData)
        {
            try
            {
                JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
                Project projectPeople = JsonConvert.DeserializeObject<Project>(j_token["Project"].ToString());
                db.Project.Update(projectPeople);
                db.SaveChanges();
                return ApiResult.True();
            }
            catch (Exception ex)
            {
                return ApiResult.False($"项目修改失败：原因{ex.Message}");
                throw;
            }
        }
        /// <summary>
        /// 返回项目参与人对象
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetProjectUsersById")]
        public ApiResult GetProjectUsersById([FromBody] DataIdRequest data)
        {
            try
            {
                var project = db.Project.FirstOrDefault(x => x.Id.Equals(data.Id));
                if (project.UserIds == null)
                {
                    return ApiResult.False("当前暂无人员请优先添加项目参与人");
                }
                var usersId = project.UserIds.Split(',');
                var users = db.Users.Where(x => usersId.Contains(x.Id.ToString())).ToList();
                return ApiResult.True(users);
            }
            catch (Exception ex)
            {
                return ApiResult.False($"项目修改失败：原因{ex.Message}");
                throw;
            }
        }

        #endregion

        #region 项目日常管理阶段
        /// <summary>
        /// 获取准备阶段的所有数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //[HttpPost("GetAllDailyManageData")]
        //public JsonResult GetAllDailyManageData([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int id = Convert.ToInt32(j_token["id"].ToString());
        //    var project = db.Project.Where(l => l.Id == id).FirstOrDefault();
        //    List<ProjectExpenseDetail> projectExpenseDetail = db.ProjectExpenseDetail.Where(x => x.ProjectId == id && !x.Delete).ToList();
        //    List<ProjectJournal> projectJournal = db.ProjectJournal.Where(x => x.ProjectId == id && !x.Delete).OrderByDescending(y => y.JournalDate).ToList();
        //    if (project.ProjectType == (int)ProjectTypeEnum.ConstructionProduction)
        //    {
        //        //List<ProjectWorkProgress> projectWorkProgress = db.ProjectWorkProgress.Where(x => x.ProjectId == id && !x.Delete).ToList();
        //        //List<ProjectDeviceUseRecord> projectDeviceUseRecord = db.ProjectDeviceUseRecord.Where(x => x.ProjectId == id && !x.Delete).ToList();
        //        //List<ProjectToolUseRecord> projectToolUseRecord = db.ProjectToolUseRecord.Where(x => x.ProjectId == id && !x.Delete).ToList();
        //        //List<ProjectOutputMeasure> projectOutputMeasure = db.ProjectOutputMeasure.Where(x => x.ProjectId == id && !x.Delete).ToList();
        //        //return Json(new { project, projectWorkProgress, projectDeviceUseRecord, projectToolUseRecord, projectJournal, projectOutputMeasure, projectExpenseDetail }, JsonRequestBehavior.DenyGet);
        //        return Json(new { project, projectJournal, projectExpenseDetail });
        //    }
        //    else
        //    {
        //        List<ProjectPeople> projectPeople = db.ProjectPeople.Where(x => x.ProjectId == id && !x.Delete && x.DataSources == (int)ProjectPeopleDataSourceEnum.DesignDev).ToList();
        //        ProjectDesignDevReview projectDesignDevReview = db.ProjectDesignDevReview.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //        ProjectReviewTrack projectReviewTrack = db.ProjectReviewTrack.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //        ProjectChangeApply projectChangeApply = db.ProjectChangeApply.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //        ProjectChangeNotice projectChangeNotice = db.ProjectChangeNotice.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //        ProjectEndApply projectEndApply = db.ProjectEndApply.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //        ProjectEndNotice projectEndNotice = db.ProjectEndNotice.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //        return Json(new { project, projectJournal, projectExpenseDetail, projectPeople, projectDesignDevReview, projectReviewTrack, projectChangeApply, projectChangeNotice, projectEndApply, projectEndNotice });
        //    }
        //}
        /// <summary>
        /// 新增项目实施进度表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult AddProjectWorkProgress(ProjectWorkProgress projectWorkProgress)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        projectWorkProgress.OperatDate = DateTime.Now;
        //        projectWorkProgress.OperatId = userid;
        //        db.ProjectWorkProgress.Add(projectWorkProgress);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 修改项目实施进度表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectWorkProgress(ProjectWorkProgress projectWorkProgress)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //项目申请表
        //        ProjectWorkProgress workProgress = db.ProjectWorkProgress.Where(x => x.Id == projectWorkProgress.Id && !x.Delete).FirstOrDefault();
        //        workProgress.EngineState = projectWorkProgress.EngineState;
        //        workProgress.ConstructionProcedure = projectWorkProgress.ConstructionProcedure;
        //        workProgress.ConstructionContents = projectWorkProgress.ConstructionContents;
        //        workProgress.StartDate = projectWorkProgress.StartDate;
        //        workProgress.EndDate = projectWorkProgress.EndDate;
        //        workProgress.Personnel = projectWorkProgress.Personnel;
        //        workProgress.LaborPersonnelCost = projectWorkProgress.LaborPersonnelCost;
        //        workProgress.SupplyMaterials = projectWorkProgress.SupplyMaterials;
        //        workProgress.UseOfFunds = projectWorkProgress.UseOfFunds;
        //        workProgress.Remark = projectWorkProgress.Remark;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增项目设备使用台账
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult AddProjectDeviceUseRecord(ProjectDeviceUseRecord projectDeviceUseRecord)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        projectDeviceUseRecord.OperatDate = DateTime.Now;
        //        projectDeviceUseRecord.OperatId = userid;
        //        db.ProjectDeviceUseRecord.Add(projectDeviceUseRecord);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 修改项目设备使用记录
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectDeviceUseRecord(ProjectDeviceUseRecord projectDeviceUseRecord)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //项目申请表
        //        ProjectDeviceUseRecord data = db.ProjectDeviceUseRecord.Where(x => x.Id == projectDeviceUseRecord.Id && !x.Delete).FirstOrDefault();
        //        data.ProjectDeviceId = projectDeviceUseRecord.ProjectDeviceId;
        //        data.DeviceName = projectDeviceUseRecord.DeviceName;
        //        data.Money = projectDeviceUseRecord.Money;
        //        data.UseStartDate = projectDeviceUseRecord.UseStartDate;
        //        data.UseEndDate = projectDeviceUseRecord.UseEndDate;
        //        data.ProjectPeopleId = projectDeviceUseRecord.ProjectPeopleId;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        
        /// <summary>
        /// 新增项目工具使用台账
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult AddProjectToolUseRecord(ProjectToolUseRecord projectToolUseRecord)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        projectToolUseRecord.OperatDate = DateTime.Now;
        //        projectToolUseRecord.OperatId = userid;
        //        db.ProjectToolUseRecord.Add(projectToolUseRecord);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 修改项目工具使用记录
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectToolUseRecord(ProjectToolUseRecord projectToolUseRecord)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //项目申请表
        //        ProjectToolUseRecord data = db.ProjectToolUseRecord.Where(x => x.Id == projectToolUseRecord.Id && !x.Delete).FirstOrDefault();
        //        if (data.ReturnUserId != 0)
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = "该工具已归还，操作失败";
        //            return new JsonResult(new { mes = mess });
        //        }
        //        data.ToolName = projectToolUseRecord.ToolName;
        //        data.Amount = projectToolUseRecord.Amount;
        //        data.BorrowDate = projectToolUseRecord.BorrowDate;
        //        data.Borrower = projectToolUseRecord.Borrower;
        //        data.Remark = projectToolUseRecord.Remark;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增项目日志使用台账
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("AddProjectJournal")]
        //public JsonResult AddProjectJournal([FromBody] dynamic formData)
        ////(ProjectJournal projectJournal, string PeoplesAll, string PeoplesAM, string PeoplesPM, List<ProjectWorkProgress> ProjectProgress, string ProjectDevice, List<ProjectToolUseRecord> ToolUseRecords)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectJournal projectJournal = JsonConvert.DeserializeObject<ProjectJournal>(j_token["projectJournal"].ToString());
        //    string PeoplesAll = j_token["PeoplesAll"].ToString();
        //    string PeoplesAM = j_token["PeoplesAM"].ToString();
        //    string PeoplesPM = j_token["PeoplesPM"].ToString();
        //    string ProjectDevice = j_token["ProjectDevice"].ToString();
        //    List<ProjectWorkProgress> ProjectProgress = JsonConvert.DeserializeObject<List<ProjectWorkProgress>>(j_token["projectWorkProgresslis"].ToString());
        //    List<ProjectToolUseRecord> ToolUseRecords = JsonConvert.DeserializeObject<List<ProjectToolUseRecord>>(j_token["ProjectToolUseRecordlis"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    int projectId = projectJournal.ProjectId;
        //    DateTime date = projectJournal.JournalDate;
        //    Message mess = new Message();
        //    //限定为项目负责人才有操作权限
        //    if (!IsProjectHeadUser(userid, projectId))
        //    {
        //        mess.IsSuccess = false;
        //        mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //        return Json(new { result = mess, data = projectJournal });
        //    }
        //    var data = db.ProjectJournal.Where(x => x.ProjectId == projectId && x.JournalDate == projectJournal.JournalDate && !x.Delete).FirstOrDefault();
        //    if (data != null)
        //    {
        //        mess.IsSuccess = false;
        //        mess.Msg = "今日日志已填写";
        //        return Json(new { result = mess, data = projectJournal });
        //    }
        //    using (var scope = new TransactionScope())
        //    {
        //        #region 添加日志
        //        projectJournal.OperatDate = DateTime.Now;
        //        projectJournal.OperatId = userid;
        //        db.ProjectJournal.Add(projectJournal);
        //        #endregion

        //        #region 添加考勤
        //        List<ProjectCheckWork> projectCheckWorks = new List<ProjectCheckWork>();
        //        var all = PeoplesAll.Split(',');
        //        var am = PeoplesAM.Split(',');
        //        var pm = PeoplesPM.Split(',');
        //        foreach (string d in all)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectCheckWork work = new ProjectCheckWork();
        //                work.ProjectId = projectId;
        //                work.CheckWorkDate = date;
        //                work.ProjectPeopleId = Convert.ToInt32(d);
        //                work.Type = (int)ProjectCheckWorkEnum.ALL;
        //                projectCheckWorks.Add(work);
        //            }
        //        }
        //        foreach (string d in am)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectCheckWork work = new ProjectCheckWork();
        //                work.ProjectId = projectId;
        //                work.CheckWorkDate = date;
        //                work.ProjectPeopleId = Convert.ToInt32(d);
        //                work.Type = (int)ProjectCheckWorkEnum.AM;
        //                projectCheckWorks.Add(work);
        //            }
        //        }
        //        foreach (string d in pm)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectCheckWork work = new ProjectCheckWork();
        //                work.ProjectId = projectId;
        //                work.CheckWorkDate = date;
        //                work.ProjectPeopleId = Convert.ToInt32(d);
        //                work.Type = (int)ProjectCheckWorkEnum.PM;
        //                projectCheckWorks.Add(work);
        //            }
        //        }
        //        AddCheckWorkData(projectCheckWorks);
        //        #endregion

        //        #region 添加实施进度
        //        foreach (var d in ProjectProgress)
        //        {
        //            d.ProjectId = projectId;
        //            d.StartDate = date;
        //            d.EndDate = date;
        //            d.OperatDate = DateTime.Now;
        //            d.OperatId = userid;
        //            db.ProjectWorkProgress.Add(d);
        //        }
        //        #endregion

        //        #region 添加设备台账
        //        var deviceData = ProjectDevice.Split(',');
        //        foreach (var d in deviceData)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectDeviceUseRecord device = new ProjectDeviceUseRecord();
        //                var da = d.Split('.');
        //                device.ProjectId = projectId;
        //                device.UseStartDate = date;
        //                device.UseEndDate = date;
        //                device.ProjectDeviceId = Convert.ToInt32(da[0]);
        //                device.DeviceName = da[1];
        //                device.OperatDate = DateTime.Now;
        //                device.OperatId = userid;
        //                db.ProjectDeviceUseRecord.Add(device);
        //            }
        //        }
        //        #endregion

        //        #region 添加工具台账
        //        foreach (var d in ToolUseRecords)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d.ToolName))
        //            {
        //                d.ProjectId = projectId;
        //                d.BorrowDate = date;
        //                d.OperatDate = DateTime.Now;
        //                d.OperatId = userid;
        //                db.ProjectToolUseRecord.Add(d);
        //            }
        //        }
        //        #endregion

        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return Json(new { result = mess, data = projectJournal });
        //}
        /// <summary>
        /// 修改项目日志使用记录
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectJournal")]
        //public JsonResult UpdateProjectJournal([FromBody] dynamic formData)
        ////(ProjectJournal projectJournal, string PeoplesAll, string PeoplesAM, string PeoplesPM, List<ProjectWorkProgress> ProjectProgress, string ProjectDevice, List<ProjectToolUseRecord> ToolUseRecords)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectJournal projectJournal = JsonConvert.DeserializeObject<ProjectJournal>(j_token["projectJournal"].ToString());
        //    string PeoplesAll = j_token["PeoplesAll"].ToString();
        //    string PeoplesAM = j_token["PeoplesAM"].ToString();
        //    string PeoplesPM = j_token["PeoplesPM"].ToString();
        //    string ProjectDevice = j_token["ProjectDevice"].ToString();
        //    List<ProjectWorkProgress> ProjectProgress = JsonConvert.DeserializeObject<List<ProjectWorkProgress>>(j_token["projectWorkProgresslis"].ToString());
        //    List<ProjectToolUseRecord> ToolUseRecords = JsonConvert.DeserializeObject<List<ProjectToolUseRecord>>(j_token["ProjectToolUseRecordlis"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectJournal.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return Json(mess);
        //        }
        //        #region 修改日志
        //        ProjectJournal data = db.ProjectJournal.Where(x => x.Id == projectJournal.Id && !x.Delete).FirstOrDefault();
        //        int projectId = projectJournal.ProjectId;
        //        DateTime date = data.JournalDate;//日期不能改变（之前的设计，因为一次性补充资料数据量过多，开放日期修改权限）
        //        DateTime newDate = projectJournal.JournalDate;
        //        data.JournalDate = projectJournal.JournalDate;
        //        data.Team = projectJournal.Team;
        //        data.Weather = projectJournal.Weather;
        //        data.WindPower = projectJournal.WindPower;
        //        data.MaxTemperature = projectJournal.MaxTemperature;
        //        data.MinTemperature = projectJournal.MinTemperature;
        //        data.ConstructionCondition = projectJournal.ConstructionCondition;
        //        data.MaterialInformation = projectJournal.MaterialInformation;
        //        data.WorkRecord = projectJournal.WorkRecord;
        //        #endregion

        //        #region 修改考勤
        //        var CheckWorks = db.ProjectCheckWork.Where(x => x.ProjectId == projectId && x.CheckWorkDate == date).ToList();
        //        foreach (var d in CheckWorks)
        //        {
        //            db.ProjectCheckWork.Remove(d);
        //        }
        //        List<ProjectCheckWork> projectCheckWorks = new List<ProjectCheckWork>();//先删除后重新添加
        //        var all = PeoplesAll.Split(',');
        //        var am = PeoplesAM.Split(',');
        //        var pm = PeoplesPM.Split(',');
        //        foreach (string d in all)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectCheckWork work = new ProjectCheckWork();
        //                work.ProjectId = projectId;
        //                work.CheckWorkDate = newDate;
        //                work.ProjectPeopleId = Convert.ToInt32(d);
        //                work.Type = (int)ProjectCheckWorkEnum.ALL;
        //                projectCheckWorks.Add(work);
        //            }
        //        }
        //        foreach (string d in am)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectCheckWork work = new ProjectCheckWork();
        //                work.ProjectId = projectId;
        //                work.CheckWorkDate = newDate;
        //                work.ProjectPeopleId = Convert.ToInt32(d);
        //                work.Type = (int)ProjectCheckWorkEnum.AM;
        //                projectCheckWorks.Add(work);
        //            }
        //        }
        //        foreach (string d in pm)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectCheckWork work = new ProjectCheckWork();
        //                work.ProjectId = projectId;
        //                work.CheckWorkDate = newDate;
        //                work.ProjectPeopleId = Convert.ToInt32(d);
        //                work.Type = (int)ProjectCheckWorkEnum.PM;
        //                projectCheckWorks.Add(work);
        //            }
        //        }
        //        AddCheckWorkData(projectCheckWorks);
        //        #endregion

        //        #region 修改实施进度
        //        var Progress = db.ProjectWorkProgress.Where(x => x.ProjectId == projectId && x.StartDate == date).ToList();
        //        foreach (var d in Progress)
        //        {
        //            db.ProjectWorkProgress.Remove(d);
        //        }
        //        foreach (var d in ProjectProgress)
        //        {
        //            d.ProjectId = projectId;
        //            d.StartDate = newDate;
        //            d.EndDate = newDate;
        //            d.OperatDate = DateTime.Now;
        //            d.OperatId = userid;
        //            db.ProjectWorkProgress.Add(d);
        //        }
        //        #endregion

        //        #region 修改设备台账
        //        var devices = db.ProjectDeviceUseRecord.Where(x => x.ProjectId == projectId && x.UseStartDate == date).ToList();
        //        foreach (var d in devices)
        //        {
        //            db.ProjectDeviceUseRecord.Remove(d);
        //        }
        //        var deviceData = ProjectDevice.Split(',');
        //        foreach (var d in deviceData)
        //        {
        //            if (!string.IsNullOrWhiteSpace(d))
        //            {
        //                ProjectDeviceUseRecord device = new ProjectDeviceUseRecord();
        //                var da = d.Split('.');
        //                device.ProjectId = projectId;
        //                device.UseStartDate = newDate;
        //                device.UseEndDate = newDate;
        //                device.ProjectDeviceId = Convert.ToInt32(da[0]);
        //                device.DeviceName = da[1];
        //                device.OperatDate = DateTime.Now;
        //                device.OperatId = userid;
        //                db.ProjectDeviceUseRecord.Add(device);
        //            }

        //        }
        //        #endregion

        //        #region 修改工具台账
        //        var tools = db.ProjectToolUseRecord.Where(x => x.ProjectId == projectId && x.BorrowDate == date).ToList();
        //        foreach (var d in tools)
        //        {
        //            db.ProjectToolUseRecord.Remove(d);
        //        }
        //        foreach (var d in ToolUseRecords)//先全部删除后重新添加
        //        {
        //            if (!string.IsNullOrWhiteSpace(d.ToolName))
        //            {
        //                d.ProjectId = projectId;
        //                d.BorrowDate = newDate;
        //                d.OperatDate = DateTime.Now;
        //                d.OperatId = userid;
        //                db.ProjectToolUseRecord.Add(d);
        //            }
        //        }
        //        #endregion

        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}
        /// <summary>
        /// 新增项目产出计量单
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult AddProjectOutputMeasure(ProjectOutputMeasure projectOutputMeasure)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectOutputMeasure.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectOutputMeasure.OperatDate = DateTime.Now;
        //        projectOutputMeasure.OperatId = userid;
        //        db.ProjectOutputMeasure.Add(projectOutputMeasure);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 修改项目产出计量单
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectOutputMeasure(ProjectOutputMeasure projectOutputMeasure)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectOutputMeasure.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        //项目申请表
        //        ProjectOutputMeasure data = db.ProjectOutputMeasure.Where(x => x.Id == projectOutputMeasure.Id && !x.Delete).FirstOrDefault();
        //        data.MeasureDate = projectOutputMeasure.MeasureDate;
        //        data.MeasureLocation = projectOutputMeasure.MeasureLocation;
        //        data.MeasureMode = projectOutputMeasure.MeasureMode;
        //        data.Amount = projectOutputMeasure.Amount;
        //        data.Unit = projectOutputMeasure.Unit;
        //        data.UnitPrice = projectOutputMeasure.UnitPrice;
        //        data.TotalPrice = projectOutputMeasure.TotalPrice;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增项目支出明细
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("AddProjectExpenseDetail")]
        //public JsonResult AddProjectExpenseDetail([FromBody] dynamic formData)
        ////(ProjectExpenseDetail projectExpenseDetail)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectExpenseDetail projectExpenseDetail = JsonConvert.DeserializeObject<ProjectExpenseDetail>(j_token["projectExpenseDetail"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectExpenseDetail.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return Json(new { result = mess, data = "" });
        //        }
        //        projectExpenseDetail.OperatDate = DateTime.Now;
        //        projectExpenseDetail.OperatId = userid;
        //        db.ProjectExpenseDetail.Add(projectExpenseDetail);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return Json(new { result = mess, data = projectExpenseDetail });
        //}
        /// <summary>
        /// 修改项目支出明细
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectExpenseDetail")]
        //public JsonResult UpdateProjectExpenseDetail([FromBody] dynamic formData)
        ////(ProjectExpenseDetail projectExpenseDetail)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectExpenseDetail projectExpenseDetail = JsonConvert.DeserializeObject<ProjectExpenseDetail>(j_token["projectExpenseDetail"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectExpenseDetail.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return Json(mess);
        //        }
        //        //项目申请表
        //        ProjectExpenseDetail data = db.ProjectExpenseDetail.Where(x => x.Id == projectExpenseDetail.Id && !x.Delete).FirstOrDefault();
        //        data.CategoryOne = projectExpenseDetail.CategoryOne;
        //        data.CategoryTwo = projectExpenseDetail.CategoryTwo;
        //        data.ChargeUserId = projectExpenseDetail.ChargeUserId;
        //        data.PayPeople = projectExpenseDetail.PayPeople;
        //        data.PayDate = projectExpenseDetail.PayDate;
        //        data.PayMethod = projectExpenseDetail.PayMethod;
        //        data.Money = projectExpenseDetail.Money;
        //        data.IsInvoice = projectExpenseDetail.IsInvoice;
        //        data.Purpose = projectExpenseDetail.Purpose;
        //        data.PurchaseNumber = projectExpenseDetail.PurchaseNumber;
        //        data.Remark = projectExpenseDetail.Remark;
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return Json(mess);
        //}
       
        /// <summary>
        /// 新增或修改项目设计开发评审表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectDesignDevReview")]
        //public JsonResult UpdateProjectDesignDevReview([FromBody] dynamic formData)
        ////(ProjectDesignDevReview projectDesignDevReview, List<ProjectPeople> ProjectPeople)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectDesignDevReview projectDesignDevReview = JsonConvert.DeserializeObject<ProjectDesignDevReview>(j_token["projectDesignDevReview"].ToString());
        //    List<ProjectPeople> ProjectPeople = JsonConvert.DeserializeObject<List<ProjectPeople>>(j_token["ProjectPeople"].ToString());

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectDesignDevReview.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectDesignDevReview.OperatDate = DateTime.Now;
        //        projectDesignDevReview.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectDesignDevReview.Id == 0)
        //        {
        //            //项目申请表
        //            db.ProjectDesignDevReview.Add(projectDesignDevReview);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectDesignDevReview data = db.ProjectDesignDevReview.Where(x => x.Id == projectDesignDevReview.Id).FirstOrDefault();
        //            data.ReviewStage = projectDesignDevReview.ReviewStage;
        //            data.NoteUserId = projectDesignDevReview.NoteUserId;
        //            data.Opinion = projectDesignDevReview.Opinion;
        //            data.Conclusion = projectDesignDevReview.Conclusion;
        //            data.Remark = projectDesignDevReview.Remark;
        //            data.OperatDate = projectDesignDevReview.OperatDate;
        //            data.OperatId = projectDesignDevReview.OperatId;

        //            //申请表中的人员配置
        //            var peoples = db.ProjectPeople.Where(x => x.ProjectId == projectDesignDevReview.ProjectId && x.DataSources == (int)ProjectPeopleDataSourceEnum.DesignDev).ToList();
        //            foreach (var p in peoples)
        //            {
        //                db.ProjectPeople.Remove(p);
        //            }
        //        }
        //        //添加人员配置
        //        foreach (var peo in ProjectPeople)
        //        {
        //            var user = db.Users.Where(x => x.Id == peo.Userid).FirstOrDefault();
        //            peo.ProjectId = projectDesignDevReview.ProjectId;
        //            peo.RoleId = user.RoleId;
        //            peo.UserName = user.UserName;
        //            peo.DataSources = (int)ProjectPeopleDataSourceEnum.DesignDev;
        //            peo.State = (int)ProjectPeopleDeviceStateEnum.OnPost;
        //            peo.OperatDate = DateTime.Now;
        //            peo.OperatId = userid;
        //            db.ProjectPeople.Add(peo);
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增或修改项目评审意见追踪表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectReviewTrack(ProjectReviewTrack projectReviewTrack)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectReviewTrack.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectReviewTrack.OperatDate = DateTime.Now;
        //        projectReviewTrack.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectReviewTrack.Id == 0)
        //        {
        //            db.ProjectReviewTrack.Add(projectReviewTrack);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectReviewTrack data = db.ProjectReviewTrack.Where(x => x.Id == projectReviewTrack.Id).FirstOrDefault();
        //            data.ReviewStage = projectReviewTrack.ReviewStage;
        //            data.TrackUserId = projectReviewTrack.TrackUserId;
        //            data.OpinionTrack = projectReviewTrack.OpinionTrack;
        //            data.ImplementationSituation = projectReviewTrack.ImplementationSituation;
        //            data.OverallEvaluation = projectReviewTrack.OverallEvaluation;
        //            data.Remark = projectReviewTrack.Remark;
        //            data.OperatId = projectReviewTrack.OperatId;
        //            data.OperatDate = projectReviewTrack.OperatDate;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增或修改项目变更申请表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectChangeApply(ProjectChangeApply projectChangeApply)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectChangeApply.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectChangeApply.OperatDate = DateTime.Now;
        //        projectChangeApply.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectChangeApply.Id == 0)
        //        {
        //            db.ProjectChangeApply.Add(projectChangeApply);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectChangeApply data = db.ProjectChangeApply.Where(x => x.Id == projectChangeApply.Id).FirstOrDefault();
        //            data.Before = projectChangeApply.Before;
        //            data.After = projectChangeApply.After;
        //            data.Reason = projectChangeApply.Reason;
        //            data.ImpactOnScope = projectChangeApply.ImpactOnScope;
        //            data.ImpactOnTime = projectChangeApply.ImpactOnTime;
        //            data.ImpactOnCost = projectChangeApply.ImpactOnCost;
        //            data.ImpactOnManpower = projectChangeApply.ImpactOnManpower;
        //            data.ImpactOnMarketr = projectChangeApply.ImpactOnMarketr;
        //            data.ImpactOnOther = projectChangeApply.ImpactOnOther;
        //            data.DepartOpinion = projectChangeApply.DepartOpinion;
        //            data.Remark = projectChangeApply.Remark;
        //            data.OperatId = projectChangeApply.OperatId;
        //            data.OperatDate = projectChangeApply.OperatDate;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增或修改项目变更通知表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectChangeNotice(ProjectChangeNotice projectChangeNotice)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectChangeNotice.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectChangeNotice.OperatDate = DateTime.Now;
        //        projectChangeNotice.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectChangeNotice.Id == 0)
        //        {
        //            db.ProjectChangeNotice.Add(projectChangeNotice);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectChangeNotice data = db.ProjectChangeNotice.Where(x => x.Id == projectChangeNotice.Id).FirstOrDefault();
        //            data.Reason = projectChangeNotice.Reason;
        //            data.Content = projectChangeNotice.Content;
        //            data.Remark = projectChangeNotice.Remark;
        //            data.OperatId = projectChangeNotice.OperatId;
        //            data.OperatDate = projectChangeNotice.OperatDate;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增或修改项目终止申请表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectEndApply(ProjectEndApply projectEndApply)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectEndApply.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectEndApply.OperatDate = DateTime.Now;
        //        projectEndApply.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectEndApply.Id == 0)
        //        {
        //            db.ProjectEndApply.Add(projectEndApply);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectEndApply data = db.ProjectEndApply.Where(x => x.Id == projectEndApply.Id).FirstOrDefault();
        //            data.Before = projectEndApply.Before;
        //            data.After = projectEndApply.After;
        //            data.Reason = projectEndApply.Reason;
        //            data.ImpactOnScope = projectEndApply.ImpactOnScope;
        //            data.ImpactOnTime = projectEndApply.ImpactOnTime;
        //            data.ImpactOnCost = projectEndApply.ImpactOnCost;
        //            data.ImpactOnManpower = projectEndApply.ImpactOnManpower;
        //            data.ImpactOnMarketr = projectEndApply.ImpactOnMarketr;
        //            data.ImpactOnOther = projectEndApply.ImpactOnOther;
        //            data.DepartOpinion = projectEndApply.DepartOpinion;
        //            data.Remark = projectEndApply.Remark;
        //            data.OperatId = projectEndApply.OperatId;
        //            data.OperatDate = projectEndApply.OperatDate;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 新增或修改项目终止通知表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectEndNotice(ProjectEndNotice projectEndNotice)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectEndNotice.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectEndNotice.OperatDate = DateTime.Now;
        //        projectEndNotice.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectEndNotice.Id == 0)
        //        {
        //            db.ProjectEndNotice.Add(projectEndNotice);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectEndNotice data = db.ProjectEndNotice.Where(x => x.Id == projectEndNotice.Id).FirstOrDefault();
        //            data.Reason = projectEndNotice.Reason;
        //            data.Remark = projectEndNotice.Remark;
        //            data.OperatId = projectEndNotice.OperatId;
        //            data.OperatDate = projectEndNotice.OperatDate;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "修改成功" : "修改失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 添加项目人员考勤
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult AddProjectCheckWorkData(List<ProjectCheckWork> projectCheckWorks)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        foreach (var p in projectCheckWorks)
        //        {
        //            p.OperatDate = DateTime.Now;
        //            p.OperatId = userid;
        //            if (p.Type == (int)ProjectCheckWorkEnum.ALL)//如果选择全天，则同时添加上午下午的考勤数据
        //            {
        //                //先判断是否已考勤
        //                var dataAM = db.ProjectCheckWork.Where(x => x.ProjectId == p.ProjectId && x.ProjectPeopleId == p.ProjectPeopleId && x.CheckWorkDate == p.CheckWorkDate && x.Type == (int)ProjectCheckWorkEnum.AM).FirstOrDefault();
        //                //先判断是否已考勤
        //                var dataPM = db.ProjectCheckWork.Where(x => x.ProjectId == p.ProjectId && x.ProjectPeopleId == p.ProjectPeopleId && x.CheckWorkDate == p.CheckWorkDate && x.Type == (int)ProjectCheckWorkEnum.PM).FirstOrDefault();
        //                if (dataAM == null)
        //                {
        //                    p.Type = (int)ProjectCheckWorkEnum.AM;
        //                    db.ProjectCheckWork.Add(p);
        //                }
        //                if (dataPM == null)
        //                {
        //                    ProjectCheckWork pNew = new ProjectCheckWork
        //                    {
        //                        Type = (int)ProjectCheckWorkEnum.PM,
        //                        ProjectId = p.ProjectId,
        //                        ProjectPeopleId = p.ProjectPeopleId,
        //                        CheckWorkDate = p.CheckWorkDate,
        //                        OperatDate = p.OperatDate,
        //                        OperatId = p.OperatId,
        //                    };
        //                    db.ProjectCheckWork.Add(pNew);
        //                }
        //            }
        //            else
        //            {
        //                //先判断是否已考勤
        //                var data = db.ProjectCheckWork.Where(x => x.ProjectId == p.ProjectId && x.ProjectPeopleId == p.ProjectPeopleId && x.CheckWorkDate == p.CheckWorkDate && x.Type == p.Type).FirstOrDefault();
        //                if (data == null)
        //                    db.ProjectCheckWork.Add(p);
        //            }
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "考勤成功" : "考勤失败，请检查人员是否已重复考勤";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        /// 添加项目人员和设备调动记录
        /// </summary>
        /// <returns></returns>
        //[HttpPost("AddProjectPeopleTransferData")]
        //public JsonResult AddProjectPeopleTransferData([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectPeopleDeviceTransfer projectPeopleDeviceTransfer = JsonConvert.DeserializeObject<ProjectPeopleDeviceTransfer>(j_token["projectPeopleDeviceTransfer"].ToString());
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var logid = TokenManage.GetTokenValues(author)[0].Value;
        //    int userid = Convert.ToInt32(logid);

        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        projectPeopleDeviceTransfer.ApplyDate = DateTime.Now;
        //        projectPeopleDeviceTransfer.OperatDate = DateTime.Now;
        //        projectPeopleDeviceTransfer.OperatId = userid;
        //        db.ProjectPeopleDeviceTransfer.Add(projectPeopleDeviceTransfer);
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "添加成功" : "添加失败";
        //    return Json(mess);
        //}
        #endregion


        #region 项目后期总结阶段
        /// <summary>
        /// 获取准备阶段的所有数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// 
        //[HttpPost("GetAllSummaryData")]
        //public JsonResult GetAllSummaryData(int id)
        //{
        //    ProjectSummary projectSummary = db.ProjectSummary.Where(x => x.ProjectId == id && !x.Delete).FirstOrDefault();
        //    return new JsonResult(new { projectSummary });
        //}
        /// <summary>
        /// 新增或修改项目终止通知表
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("UpdateProjectSummary")]
        //public JsonResult UpdateProjectSummary([FromBody] dynamic formData)

        //// ( ProjectSummary projectSummary)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    ProjectSummary projectSummary = JsonConvert.DeserializeObject<ProjectSummary>(j_token["data"].ToString());
        //    Project pro = db.Project.Where(x => x.Id == projectSummary.ProjectId).FirstOrDefault();
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    Message mess = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        //限定为项目负责人才有操作权限
        //        if (!IsProjectHeadUser(userid, projectSummary.ProjectId))
        //        {
        //            mess.IsSuccess = false;
        //            mess.Msg = PublicTool.GetDescription(MessageTextEnum.HeadUserIdRight);
        //            return new JsonResult(new { mes = mess });
        //        }
        //        projectSummary.OperatDate = DateTime.Now;
        //        projectSummary.OperatId = userid;
        //        //id为0代表是新增数据，反之则为修改数据
        //        if (projectSummary.Id == 0)
        //        {
        //            db.ProjectSummary.Add(projectSummary);
        //        }
        //        else
        //        {
        //            //项目申请表
        //            ProjectSummary data = db.ProjectSummary.Where(x => x.Id == projectSummary.Id).FirstOrDefault();
        //            data.ActualStartDate = projectSummary.ActualStartDate;
        //            data.ActualEndDate = projectSummary.ActualEndDate;
        //            data.ActualMoney = projectSummary.ActualMoney;
        //            data.ActualPeopleAmount = projectSummary.ActualPeopleAmount;
        //            data.PlanCost = projectSummary.PlanCost;
        //            data.ActualCost = projectSummary.ActualCost;
        //            data.BusinessSituation = projectSummary.BusinessSituation;
        //            data.BusinessProblems = projectSummary.BusinessProblems;
        //            data.BusinessHarvest = projectSummary.BusinessHarvest;
        //            data.TechnicalSituation = projectSummary.TechnicalSituation;
        //            data.TechnicalProblems = projectSummary.TechnicalProblems;
        //            data.TechnicalHarvest = projectSummary.TechnicalHarvest;
        //            data.ManagementSituation = projectSummary.ManagementSituation;
        //            data.ManagementProblems = projectSummary.ManagementProblems;
        //            data.ManagementHarvest = projectSummary.ManagementHarvest;
        //            data.OperatDate = projectSummary.OperatDate;
        //            data.OperatId = projectSummary.OperatId;
        //        }
        //        mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        scope.Complete();
        //    }
        //    mess.Msg = mess.IsSuccess ? "操作成功" : "操作失败";
        //    return new JsonResult(new { mes = mess });
        //}
        /// <summary>
        #endregion


        #region 新加接口信息



        #region 项目财务数据阶段
        /// <summary>
        /// 获取所有的项目财务数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private JsonResult GetAllProjectFinanceData(int id)
        {
            Project pro = db.Project.Where(x => x.Id == id).FirstOrDefault();
            return new JsonResult(pro);
        }
        /// <summary>
        /// 新增或修改项目财务信息
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateProjectFinance(Project project)
        {
            Project pro = db.Project.Where(x => x.Id == project.Id).FirstOrDefault();
            //var right = PublicTool.GetRight().UserData;
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            Users user = PublicTool.GetUsers(userId);
            var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
            Message mess = new Message();
            //if (!right.Contains(FinanceAudit) && !right.Contains(FinanceCashier))
            //if (user.DepartmentId != Convert.ToInt32(AuditRightDepartEnum.FinanceDepart))
            if (!right.Contains(((int)AuditRightPeopleEnum.FinanceAccounting).ToString()) || !right.Contains(((int)AuditRightPeopleEnum.FinanceCashier).ToString()))
            {
                mess.IsSuccess = false;
                mess.Msg = "您无操作权限，请联系财务人员";
                return new JsonResult(new { mes = mess });
            }
            using (var scope = new TransactionScope())
            {
                pro.CollectionAmount = project.CollectionAmount;
                //pro.BadMoney = project.BadMoney;
                //pro.WriteOffTax = project.WriteOffTax;
                //pro.SettleMoney = project.SettleMoney;
                //pro.PersonLoan = project.PersonLoan;
                //pro.PurchaseCost = project.PurchaseCost;
                //pro.LaborCost = project.LaborCost;
                //pro.MaterialCost = project.MaterialCost;
                //pro.MachineryCost = project.MachineryCost;
                //pro.OtherDirectCost = project.OtherDirectCost;
                //pro.SubcontractingCost = project.SubcontractingCost;
                //pro.WriteOffRate = project.WriteOffRate;
                //pro.ManagementPersonCost = project.ManagementPersonCost;
                //pro.WelfareCost = project.WelfareCost;
                //pro.FixedAssetsCost = project.FixedAssetsCost;
                //pro.LowValueCost = project.LowValueCost;
                //pro.OfficeCost = project.OfficeCost;
                //pro.TravelCost = project.TravelCost;
                //pro.BusinessCost = project.BusinessCost;
                //pro.SafetyCost = project.SafetyCost;
                //pro.VehicleCost = project.VehicleCost;
                //pro.OtherIndirectCost = project.OtherIndirectCost;
                //pro.OperatingCost = project.OperatingCost;
                mess.IsSuccess = db.SaveChanges() > 0 ? true : false;
                scope.Complete();
            }
            mess.Msg = mess.IsSuccess ? "操作成功" : "操作失败";
            return new JsonResult(new { mes = mess });
        }
        /// <summary>
        #endregion

        #region 项目报表
        /// <summary>
        /// 项目备案报表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetProjectRecordlReport")]
        public JsonResult GetProjectRecordlReport([FromBody] dynamic formData)
        {
            JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
            int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
            var data = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
            //var applyUser = db.Users.Where(x => x.Id == data.ApplyUserid).FirstOrDefault();
            //var ApplyUserName = applyUser.UserName;
            //var ApplyUserPhone = applyUser.Phone;
            //var managementHelpUser = db.Users.Where(x => x.Id == data.ManagementHelpUserid).FirstOrDefault();
            //var Department = db.Department.Where(x => x.Id == data.DepartmentId).FirstOrDefault();
            //var ImplementDepartment = db.Department.Where(x => x.Id == data.ImplementDepartment).FirstOrDefault();
            //var managementHelpUserName = managementHelpUser == null ? "" : managementHelpUser.UserName;
            //var DepartmentName = Department == null ? "" : Department.DepartmentName;
            //var ImplementDepartmentName = ImplementDepartment == null ? "" : ImplementDepartment.DepartmentName;
            return new JsonResult(new { data.OperatDate, data.Remark });
        }
        /// <summary>
        /// 项目设备使用计划报表
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult GetProjectDeviceReport(int ProjectId)
        //{
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectDevice> dataProjectDevices = db.ProjectDevice.Where(x => !x.Delete && x.ProjectId == ProjectId && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
        //    return new JsonResult(new { dataProject, dataProjectDevices });
        //}
        /// <summary>
        /// 项目工作计划报表
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectWorkPlanReport")]
        //public JsonResult GetProjectWorkPlanReport([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectWorkPlan> dataProjectWorkPlans = db.ProjectWorkPlan.Where(x => !x.Delete && x.ProjectId == ProjectId).OrderBy(y => y.PlanStartDate).ToList();
        //    return new JsonResult(new { dataProject, dataProjectWorkPlans });
        //}
        /// <summary>
        /// 项目人员计划报表
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectPeopleReport")]
        //public JsonResult GetProjectPeopleReport([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectPeople> dataProjectPeoples = db.ProjectPeople.Where(x => !x.Delete && x.ProjectId == ProjectId && x.DataSources == (int)ProjectPeopleDataSourceEnum.PeoplePlan && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
        //    return new JsonResult(new { dataProject, dataProjectPeoples });
        //}
        /// <summary>
        /// 项目实施进度报表
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectWorkProgressReport")]
        //public JsonResult GetProjectWorkProgressReport([FromBody] dynamic formData)
        ////(int ProjectId)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectWorkProgress> ProjectWorkProgress = db.ProjectWorkProgress.Where(x => !x.Delete && x.ProjectId == ProjectId).OrderBy(y => y.WorkPlanId).ThenByDescending(x => x.StartDate).ToList();
        //    var dataProjectWorkProgress = from p in ProjectWorkProgress
        //                                  join plan in db.ProjectWorkPlan on p.WorkPlanId equals plan.Id
        //                                  select new
        //                                  {
        //                                      p.Id,
        //                                      p.ProjectId,
        //                                      p.WorkPlanId,
        //                                      p.Quantity,
        //                                      p.StartDate,
        //                                      p.Remark,
        //                                      plan.ConstructionProcedure,
        //                                      plan.ConstructionContents,
        //                                      plan.EngineState,
        //                                      plan.PlanEndDate,
        //                                      plan.TotalQuantity,
        //                                      plan.Unit
        //                                  };
        //    var typelis = dataProjectWorkProgress.GroupBy(x => x.WorkPlanId).ToList().Select(x => x.Key).ToList();
        //    return new JsonResult(new { dataProject, dataProjectWorkProgress, typelis });
        //}
        /// <summary>
        /// 项目设备使用台账
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectDeviceUseRecordReport")]
        //public JsonResult GetProjectDeviceUseRecordReport([FromBody] dynamic formData)
        ////(int ProjectId, string deviceName)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    string deviceName = j_token["deviceName"].ToString();
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectDeviceUseRecord> dataProjectDeviceUseRecords = db.ProjectDeviceUseRecord.Where(x => !x.Delete && x.ProjectId == ProjectId && x.DeviceName == deviceName).OrderByDescending(y => y.UseStartDate).ToList();
        //    return new JsonResult(new { dataProject, dataProjectDeviceUseRecords });
        //}
        /// <summary>
        /// 项目工具使用台账
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectToolUseRecordReport")]
        //public JsonResult GetProjectToolUseRecordReport([FromBody] dynamic formData)
        ////(int ProjectId)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectToolUseRecord> dataProjectToolUseRecords = db.ProjectToolUseRecord.Where(x => !x.Delete && x.ProjectId == ProjectId).OrderByDescending(y => y.BorrowDate).ToList();
        //    return new JsonResult(new { dataProject, dataProjectToolUseRecords });
        //}
        /// <summary>
        /// 项目人员考勤报表
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectCheckWorkReport")]
        //public JsonResult GetProjectCheckWorkReport([FromBody] dynamic formData)
        ////(int ProjectId, int year, int month)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    int year = Convert.ToInt32(j_token["year"].ToString());
        //    int month = Convert.ToInt32(j_token["month"].ToString());
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectCheckWork> dataProjectCheckWorks = db.ProjectCheckWork.Where(x => !x.Delete && x.ProjectId == ProjectId && x.CheckWorkDate.Year == year && x.CheckWorkDate.Month == month).OrderBy(y => y.CheckWorkDate).ToList();
        //    return new JsonResult(new { dataProject, dataProjectCheckWorks });
        //}


        /// <summary>
        /// 项目借款使用明细报表
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetProjectExpenseDetailReport")]
        //public JsonResult GetProjectExpenseDetailReport([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    var dataProject = db.Project.Where(x => !x.Delete && x.Id == ProjectId).FirstOrDefault();
        //    List<ProjectExpenseDetail> dataProjectExpenseDetails = db.ProjectExpenseDetail.Where(x => !x.Delete && x.ProjectId == ProjectId).OrderByDescending(x => x.PayDate).ToList();
        //    decimal sumPrice = 0;
        //    if (dataProjectExpenseDetails.Count > 0)
        //    {
        //        sumPrice = dataProjectExpenseDetails.Sum(y => y.Money);
        //    }
        //    return new JsonResult(new { dataProject, dataProjectExpenseDetails, sumPrice });
        //}
        #endregion


        #region 出库单和出库记录
        /// 添加项目出库单，并且生成项目物资出库记录，但是不改变物资数量
        /// </summary>
        /// <param name="inboundOrder"></param>
        /// <returns></returns>
        //[HttpPost("AddProjectOutboundOrderContent")]
        //public async Task<JsonResult> AddProjectOutboundOrderContent([FromBody] dynamic formData)
        ////(ProjectDesignDevReview projectDesignDevReview, List<ProjectPeople> ProjectPeople)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    var projectId = Convert.ToInt32(j_token["projectId"].ToString());
        //    List<ProjectOutboundRecord> records = JsonConvert.DeserializeObject<List<ProjectOutboundRecord>>(j_token["records"].ToString());

        //    //
        //    //     (List<ProjectOutboundRecord> records, int projectId)
        //    // {
        //    //

        //    Message message = new Message();
        //    PublicMethodApiController pub = new PublicMethodApiController(db);

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    var data = db.ProjectPeople.Where(x => x.ProjectId == projectId && x.Userid == userId && x.DataSources == (int)ProjectPeopleDataSourceEnum.PeoplePlan && !x.Delete).FirstOrDefault();
        //    if (data == null)
        //    {
        //        message.IsSuccess = false;
        //        message.Msg = "您不是该项目成员，不能进行该项目下的物资出库操作";
        //        return new JsonResult(message);
        //    }
        //    ProjectOutboundOrder outboundOrder = new ProjectOutboundOrder();
        //    using (var scope = new TransactionScope())
        //    {
        //        //生成项目出库单
        //        outboundOrder.ProjectId = projectId;
        //        outboundOrder.Receiver = userId;
        //        outboundOrder.OperatDate = DateTime.Now;
        //        outboundOrder.OperatId = userId;
        //        outboundOrder.ProjectOutboundNumber = pub.SetMaxPurchaseNumber(db.ProjectOutboundOrder.Select(x => x.ProjectOutboundNumber).Max());
        //        outboundOrder.State = (int)ProjectOutboundOrderStateEnum.WaitApprove;
        //        db.ProjectOutboundOrder.Add(outboundOrder);
        //        #region 构造项目物资出库记录
        //        foreach (var re in records)
        //        {
        //            ProjectOutboundRecord record = new ProjectOutboundRecord();
        //            record.DeviceId = re.DeviceId;
        //            record.ProjectOutboundNumber = outboundOrder.ProjectOutboundNumber;
        //            record.Amount = re.Amount;
        //            db.ProjectOutboundRecord.Add(record);
        //        }
        //        #endregion
        //        message.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        //提交事务
        //        scope.Complete();
        //    }
        //    message.Msg = outboundOrder.ProjectOutboundNumber;
        //    ////保存成功后就通知项目负责人来进行审核
        //    //if (message.IsSuccess)
        //    //{
        //    //    PublicTool.BuildSendProjectMaterialMesAsync(projectId, outboundOrder.Receiver, "项目出库单", outboundOrder.ProjectOutboundNumber);
        //    //    PublicTool.DingDingSendProjectMessageMesAsync(projectId, outboundOrder.Receiver, "项目出库单", outboundOrder.ProjectOutboundNumber);
        //    //}
        //    return new JsonResult(message);
        //}
        /// <summary>
        /// 更新出库信息
        /// </summary>
        /// <param name="Purchase"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectOutboundOrderContent(List<ProjectOutboundRecord> records)
        //{
        //    Message message = new Message();
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    if (records.Count > 0)
        //    {
        //        ProjectOutboundRecord re = records.FirstOrDefault();
        //        var outbound = db.ProjectOutboundOrder.Where(x => x.ProjectOutboundNumber == re.ProjectOutboundNumber).FirstOrDefault();
        //        if (!PublicTool.ValidateRightUser(outbound.Receiver, userId) && !PublicTool.ValidateRightProjectHeadUser(outbound.ProjectId, userId))
        //        {
        //            message.IsSuccess = false;
        //            message.Msg = "本人或者项目负责人才能进行修改";
        //            return new JsonResult(message);
        //        }
        //        if (outbound.State > (int)ProjectOutboundOrderStateEnum.WaitApprove)
        //        {
        //            message.IsSuccess = false;
        //            message.Msg = "该出库单已审核，不能修改";
        //            return new JsonResult(message);
        //        }

        //        //更新商品信息
        //        foreach (ProjectOutboundRecord record in records)
        //        {
        //            var r = db.ProjectOutboundRecord.Find(record.Id);
        //            r.Amount = record.Amount;
        //        }
        //        message.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //    }
        //    return new JsonResult(message);
        //}
        ///// <summary>
        ///// 出库单审核
        ///// </summary>
        ///// <param name="arrDel">id集合</param>
        ///// <returns></returns>
        //[HttpPost]
        //public JsonResult AuditProjectOutboundOrderContent(string ProjectOutboundNumber)
        //{
        //    Message mes = new Message();
        //    mes.Msg = PublicTool.GetDescription(MessageTextEnum.WrongState);
        //    ProjectOutboundOrder outbound = db.ProjectOutboundOrder.Where(l => l.ProjectOutboundNumber == ProjectOutboundNumber).FirstOrDefault();
        //    var outboundRecords = db.ProjectOutboundRecord.Where(x => x.ProjectOutboundNumber == ProjectOutboundNumber && !x.Delete).ToList();



        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);

        //    var name = PublicTool.GetUsers(userId).UserName;
        //    using (var scope = new TransactionScope())
        //    {
        //        if (PublicTool.ValidateRightProjectHeadUser(outbound.ProjectId, userId))
        //        {
        //            if (outbound.State == (int)ProjectOutboundOrderStateEnum.WaitApprove)
        //            {
        //                List<string> OutboundNumbers = new List<string>();
        //                var outboundOrders = db.OutboundOrder.Where(x => !x.Delete && x.OutboundProject == outbound.ProjectId).ToList();
        //                foreach (var o in outboundOrders)
        //                {
        //                    if (o.IsAuditEnd)
        //                    {
        //                        OutboundNumbers.Add(o.OutboundNumber);
        //                    }
        //                }
        //                //var outboundRecordsql = "select * from outboundrecord where IsReturn=0 and OutboundNumber in (select OutboundNumber FROM outboundorder where OutboundProject=" + outbound.ProjectId + " and (State=4 or state=8) and Delete=0)";
        //                var outboundrecords = db.OutboundRecord.Where(x => !x.IsReturn && OutboundNumbers.Contains(x.OutboundNumber)).ToList();

        //                var ProjectOutboundOrders = db.ProjectOutboundOrder.Where(x => x.ProjectId == outbound.ProjectId && x.State > (int)ProjectOutboundOrderStateEnum.WaitApprove && !x.Delete).ToList();
        //                var ProjectOutboundOrderNumbers = ProjectOutboundOrders.Select(y => y.ProjectOutboundNumber).ToList();
        //                var ProjectOutboundRecords = db.ProjectOutboundRecord.Where(y => ProjectOutboundOrderNumbers.Contains(y.ProjectOutboundNumber) && !y.Delete).ToList();
        //                #region 先判断项目物资库中该物资的库存数量是否足够
        //                foreach (var record in outboundRecords)
        //                {
        //                    //计算该物资出库到项目上的总数量、已经归还的消耗数量、损坏数量
        //                    var outboundrecord = outboundrecords.Where(x => x.DeviceId == record.DeviceId).ToList();
        //                    var Amount = outboundrecord.Sum(x => x.Amount);
        //                    var ConsumeAmount = outboundrecord.Sum(x => x.ConsumeAmount);
        //                    var DamageAmount = outboundrecord.Sum(x => x.DamageAmount);

        //                    //计算该物资出库到项目上的已被借用的总数量、已经归还的消耗数量、损坏数量
        //                    var ProjectOutboundRecorddata = ProjectOutboundRecords.Where(y => y.DeviceId == record.DeviceId).ToList();
        //                    var ProjectAmount = ProjectOutboundRecorddata.Sum(x => x.Amount);
        //                    var ProjectReturnAmount = ProjectOutboundRecorddata.Sum(x => x.ReturnAmount);
        //                    //计算该物资在该项目上的库存数量
        //                    var StockAmount = Amount - ConsumeAmount - DamageAmount - ProjectAmount + ProjectReturnAmount;
        //                    if (StockAmount < record.Amount)
        //                    {
        //                        Device device = db.Device.Find(record.DeviceId);
        //                        mes.IsSuccess = false;
        //                        mes.Msg = device.DeviceName + "的库存不足，无法完成项目出库，请先更改出库数量";
        //                        return new JsonResult(mes);
        //                    }
        //                }
        //                #endregion
        //                outbound.State = (int)ProjectOutboundOrderStateEnum.AlreadyApprove1;
        //                outbound.AuditUserId1 = userId;
        //                outbound.AuditTime1 = DateTime.Now;
        //                mes.Remark = name;
        //                mes.IsSuccess = true;
        //                mes.Msg = "审批完成";
        //            }
        //        }
        //        else
        //        {
        //            mes.IsSuccess = false;
        //            mes.Msg = "您无签批权限";
        //        }
        //        mes.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        //提交事务
        //        scope.Complete();
        //    }
        //    return new JsonResult(mes);
        //}
        #endregion

        #region 归还单和归还记录
        /// <summary>
        /// 获取项目物资库信息
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult GetProjectReturnRecord(string ProjectReturnOrderNumber)
        //{
        //    var ProjectReturnRecorddata = db.ProjectReturnRecord.Where(y => ProjectReturnOrderNumber == y.ProjectReturnOrderNumber && !y.Delete).ToList();
        //    var ProjectReturnRecords = from r in ProjectReturnRecorddata
        //                               join or in db.ProjectOutboundRecord on r.ProjectOutboundRecordId equals or.Id
        //                               join d in db.Device on or.DeviceId equals d.Id
        //                               select new
        //                               {
        //                                   r.Id,
        //                                   or.DeviceId,
        //                                   r.ProjectReturnOrderNumber,
        //                                   r.ReturnAmount,
        //                                   r.ConsumeAmount,
        //                                   r.DamageAmount,
        //                                   WaitReturnAmount = or.Amount - or.ReturnAmount - or.ConsumeAmount - or.DamageAmount,
        //                                   d.DeviceName,
        //                                   d.DeviceModel,
        //                                   d.DeviceNumber,
        //                                   d.Unit
        //                               };
        //    return new JsonResult(ProjectReturnRecords);
        //}
        /// <summary>
        /// 添加项目出库单，并且生成项目物资出库记录，但是不改变物资数量
        /// </summary>
        /// <param name="inboundOrder"></param>
        /// <returns></returns>
        //[HttpPost]
        //public async Task<JsonResult> AddProjectReturnOrderContent(List<ProjectReturnRecord> records, int projectId)
        //{
        //    Message message = new Message();
        //    PublicMethodApiController pub = new PublicMethodApiController(db);



        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
        //    ProjectReturnOrder outboundOrder = new ProjectReturnOrder();
        //    using (var scope = new TransactionScope())
        //    {
        //        //生成项目归还单
        //        outboundOrder.ProjectId = projectId;
        //        outboundOrder.Returner = userId;
        //        outboundOrder.OperatDate = DateTime.Now;
        //        outboundOrder.OperatId = userId;
        //        outboundOrder.ProjectReturnOrderNumber = pub.SetMaxPurchaseNumber(db.ProjectReturnOrder.Select(x => x.ProjectReturnOrderNumber).Max());
        //        outboundOrder.State = (int)ProjectReturnOrderStateEnum.WaitApprove;
        //        db.ProjectReturnOrder.Add(outboundOrder);
        //        #region 构造项目物资归还记录
        //        foreach (var re in records)
        //        {
        //            ProjectReturnRecord record = new ProjectReturnRecord();
        //            record.ProjectOutboundRecordId = re.Id;
        //            record.ProjectReturnOrderNumber = outboundOrder.ProjectReturnOrderNumber;
        //            record.ReturnAmount = re.ReturnAmount;
        //            record.DamageAmount = re.DamageAmount;
        //            record.ConsumeAmount = re.ConsumeAmount;
        //            db.ProjectReturnRecord.Add(record);
        //        }
        //        #endregion
        //        message.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        //提交事务
        //        scope.Complete();
        //    }
        //    message.Msg = outboundOrder.ProjectReturnOrderNumber;
        //    ////保存成功后就通知项目负责人来进行审核
        //    //if (message.IsSuccess)
        //    //{
        //    //    PublicTool.BuildSendProjectMaterialMesAsync(projectId, outboundOrder.Returner, "项目归还单", outboundOrder.ProjectReturnOrderNumber);
        //    //    PublicTool.DingDingSendProjectMessageMesAsync(projectId, outboundOrder.Returner, "项目归还单", outboundOrder.ProjectReturnOrderNumber);
        //    //}
        //    return new JsonResult(message);
        //}
        /// <summary>
        /// 删除项目归还单
        /// </summary>
        /// <param name="arrDel">id集合</param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult DeleteProjectReturnOrderContent(int id)
        //{

        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
        //    Message mes = new Message();
        //    using (var scope = new TransactionScope())
        //    {
        //        var obj = db.ProjectReturnOrder.Where(x => x.Id == id && !x.Delete).FirstOrDefault();
        //        if (obj == null || obj.State > (int)ProjectReturnOrderStateEnum.WaitApprove)
        //        {
        //            mes.IsSuccess = false;
        //            mes.Msg = "该项目归还单不存在或者已经通过审核，无法删除";
        //            return new JsonResult(mes);
        //        }
        //        //只能申请人本人或者项目负责人可以操作
        //        if (!PublicTool.ValidateRightUser(obj.Returner, userId) && !PublicTool.ValidateRightProjectHeadUser(obj.ProjectId, userId))
        //        {
        //            mes.IsSuccess = false;
        //            mes.Msg = "操作失败，只能本人或者项目负责人才能删除提交的项目归还单";
        //            return new JsonResult(mes);
        //        }
        //        obj.Delete = true;
        //        obj.OperatId = userId;
        //        //将该出库单下的物资也改为已删除状态
        //        List<ProjectReturnRecord> devs = db.ProjectReturnRecord.Where(r => r.ProjectReturnOrderNumber == obj.ProjectReturnOrderNumber && !r.Delete).ToList();
        //        foreach (var g in devs)
        //        {
        //            g.Delete = true;
        //        }
        //        mes.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        //提交事务
        //        scope.Complete();
        //    }
        //    return new JsonResult(mes);
        //}
        /// <summary>
        /// 更新归还单信息
        /// </summary>
        /// <param name="Purchase"></param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult UpdateProjectReturnOrderContent(List<ProjectReturnRecord> records)
        //{
        //    Message message = new Message();
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
        //    if (records.Count > 0)
        //    {
        //        ProjectReturnRecord re = records.FirstOrDefault();
        //        var outbound = db.ProjectReturnOrder.Where(x => x.ProjectReturnOrderNumber == re.ProjectReturnOrderNumber).FirstOrDefault();
        //        if (!PublicTool.ValidateRightUser(outbound.Returner, userId) && !PublicTool.ValidateRightProjectHeadUser(outbound.ProjectId, userId))
        //        {
        //            message.IsSuccess = false;
        //            message.Msg = "本人或者项目负责人才能进行修改";
        //            return new JsonResult(message);
        //        }
        //        if (outbound.State > (int)ProjectReturnOrderStateEnum.WaitApprove)
        //        {
        //            message.IsSuccess = false;
        //            message.Msg = "该出库单已审核，不能修改";
        //            return new JsonResult(message);
        //        }
        //        //更新商品信息
        //        foreach (ProjectReturnRecord record in records)
        //        {
        //            var r = db.ProjectReturnRecord.Find(record.Id);
        //            r.ReturnAmount = record.ReturnAmount;
        //            r.DamageAmount = record.DamageAmount;
        //            r.ConsumeAmount = record.ConsumeAmount;
        //        }
        //        message.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //    }
        //    return new JsonResult(message);
        //}
        /// <summary>
        /// 归还单审核
        /// </summary>
        /// <param name="arrDel">id集合</param>
        /// <returns></returns>
        //[HttpPost]
        //public JsonResult AuditProjectReturnOrderContent(string ProjectReturnOrderNumber)
        //{
        //    Message mes = new Message();
        //    mes.Msg = PublicTool.GetDescription(MessageTextEnum.WrongState);
        //    ProjectReturnOrder outbound = db.ProjectReturnOrder.Where(l => l.ProjectReturnOrderNumber == ProjectReturnOrderNumber).FirstOrDefault();
        //    var outboundRecords = db.ProjectReturnRecord.Where(x => x.ProjectReturnOrderNumber == ProjectReturnOrderNumber && !x.Delete).ToList();
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    var right = Convert.ToString(TokenManage.GetTokenValues(author)[2].Value);
        //    var name = PublicTool.GetUsers(userId).UserName;
        //    using (var scope = new TransactionScope())
        //    {
        //        if (PublicTool.ValidateRightProjectHeadUser(outbound.ProjectId, userId))
        //        {
        //            if (outbound.State == (int)ProjectReturnOrderStateEnum.WaitApprove)
        //            {
        //                #region 归还记录中的数量同步改变出库记录中的归还、消耗、损坏数量
        //                foreach (ProjectReturnRecord re in outboundRecords)
        //                {
        //                    ProjectOutboundRecord record = db.ProjectOutboundRecord.Find(re.ProjectOutboundRecordId);
        //                    if (record.IsReturn)
        //                        break;
        //                    record.ReturnAmount += re.ReturnAmount;
        //                    record.DamageAmount += re.DamageAmount;
        //                    record.ConsumeAmount += re.ConsumeAmount;
        //                    var allAmount = record.ReturnAmount + record.DamageAmount + record.ConsumeAmount;
        //                    if (record.Amount < allAmount)
        //                    {
        //                        var dev = db.Device.Find(record.DeviceId);
        //                        mes.IsSuccess = false;
        //                        mes.Msg = dev.DeviceName + "的归还数量、消耗数量、损坏数量之和大于待归数量，归还失败，请修改后重试";
        //                        return new JsonResult(mes);
        //                    }
        //                    if (record.Amount == allAmount)
        //                        record.IsReturn = true;

        //                }
        //                #endregion
        //                outbound.State = (int)ProjectReturnOrderStateEnum.AlreadyApprove1;
        //                outbound.AuditUserId1 = userId;
        //                outbound.AuditTime1 = DateTime.Now;
        //                mes.Remark = name;
        //                mes.IsSuccess = true;
        //                mes.Msg = "审批完成";
        //            }
        //        }
        //        else
        //        {
        //            mes.IsSuccess = false;
        //            mes.Msg = "您无签批权限";
        //        }
        //        mes.IsSuccess = db.SaveChanges() > 0 ? true : false;
        //        //提交事务
        //        scope.Complete();
        //    }
        //    return new JsonResult(mes);
        //}

        #endregion

        #endregion

        #region 公共方法
        /// <summary>
        /// 获取某个项目下的项目设备
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns> 
        //[HttpPost("GetProjectDevice")]
        //public string GetProjectDevice([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    List<ProjectDevice> projectDevices = db.ProjectDevice.Where(x => !x.Delete && x.ProjectId == ProjectId && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost).ToList();
        //    if (projectDevices.Count > 0)
        //    {
        //        var str = JsonConvert.SerializeObject(projectDevices);
        //        return str;
        //    }
        //    return "";
        //}
        /// <summary>
        /// 获取某个项目下的计划表中的人员
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("GetProjectPeople")]
        //public JsonResult GetProjectPeople([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    List<ProjectPeople> projectPeople = db.ProjectPeople.Where(x => !x.Delete && x.ProjectId == ProjectId && x.DataSources == (int)ProjectPeopleDataSourceEnum.PeoplePlan/* && x.State == (int)ProjectPeopleDeviceStateEnum.OnPost*/).ToList();
        //    return Json(projectPeople);
        //}
        /// <summary>
        /// 获取某个项目下的项目实施计划内容
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        //[HttpPost("GetProjectWorkPlan")]
        //public JsonResult GetProjectWorkPlan([FromBody] dynamic formData)
        //{
        //    JToken j_token = JsonConvert.DeserializeObject<JToken>(formData.ToString());
        //    int ProjectId = Convert.ToInt32(j_token["ProjectId"].ToString());
        //    List<ProjectWorkPlan> projectWorkPlans = db.ProjectWorkPlan.Where(x => !x.Delete && x.ProjectId == ProjectId).ToList();
        //    return Json(projectWorkPlans);
        //}
        /// <summary>
        /// 添加项目人员考勤数据
        /// </summary>
        /// <returns></returns>
        //private void AddCheckWorkData(List<ProjectCheckWork> projectCheckWorks)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    var userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    using (var scope = new TransactionScope())
        //    {
        //        foreach (var p in projectCheckWorks)
        //        {
        //            p.OperatDate = DateTime.Now;
        //            p.OperatId = userid;
        //            ////先判断是否已考勤
        //            //var data = db.ProjectCheckWork.Where(x => x.ProjectId == p.ProjectId && x.ProjectPeopleId == p.ProjectPeopleId && x.CheckWorkDate == p.CheckWorkDate && (x.Type == p.Type||x.Type==(int)ProjectCheckWorkEnum.ALL)).FirstOrDefault();
        //            //if (data == null)
        //            db.ProjectCheckWork.Add(p);
        //        }
        //        //db.SaveChanges();
        //        scope.Complete();
        //    }
        //}
        /// <summary>
        /// 判断是否有项目负责人权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="ProjectId"></param>
        /// <returns></returns>
        private bool IsProjectHeadUser(int userId, int ProjectId)
        {
            var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            var vuserId = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
            bool isHeadUser = false;
            if (userId == 0)
                userId = vuserId;
            Project project = db.Project.Find(ProjectId);
            if (project != null && Convert.ToInt32(project.HeadUserId) == userId)
                isHeadUser = true;
            return isHeadUser;
        }
        #endregion
        #endregion
    }
}

